CodexBloom - Programming Q&A Platform

TypeScript: Type Inference implementing Function Parameters in a Class Method

πŸ‘€ Views: 85 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-21
typescript class type-inference

I'm migrating some code and Quick question that's been bugging me - I've looked through the documentation and I'm still confused about I'm working with a type inference scenario in TypeScript when trying to define a method in a class that should accept a callback function. The method is supposed to accept a function that takes a string and returns a number, but TypeScript seems to struggle with inferring the correct types. Here’s the code I have: ```typescript class Processor { processData(callback: (input: string) => number) { const result = callback('Test'); console.log(result); } } const processor = new Processor(); // This callback works fine processor.processData((input) => input.length); // But if I try to do this... const invalidCallback = (input: string) => { return input.split('').length; }; processor.processData(invalidCallback); ``` I get a TypeScript behavior that says `Argument of type '(input: string) => number' is not assignable to parameter of type '(input: string) => number'.` This makes no sense since both functions seem to match the expected signature. I've tried explicitly typing the `invalidCallback` function and using arrow functions, but the behavior continues. Is there something about how TypeScript infers types in this context that I'm missing? I’m using TypeScript version 4.5.4 and I’ve also checked my tsconfig settings, but I need to seem to find any issues there. Any insights would be greatly appreciated! My development environment is CentOS. Is there a simpler solution I'm overlooking?