I'm trying to write a Typescript interface, then write a class that implements that interface.
The problem is that I can't seem to get the method signatures from the interface to apply to the class.
Here's a slimmed-down example:
export interface Foo {
bar(value: string): void;
}
export class MyFoo implements Foo {
// ✔️ Typescript error:
// Property 'bar' is missing in type 'MyFoo' but required in type 'Foo'
}
export class MyFoo implements Foo {
// value is inferred as `any` instead of `string`,
// and there aren't any errors with the return type mismatch
bar(value) { return true; }
}
It seems that the compiler is aware that the bar method should exist, but doesn't preserve the signature of it for some reason.
seems that the compiler is aware that the bar method should exist, but doesn't preserve the signature of it for some reason.
Correct. Reasons are covered here : https://github.com/Microsoft/TypeScript/pull/6118#issuecomment-216595207
So it is made the responsibility of the developer to add the annotations they need.
Type any can be assigned to any other type in TypeScript. You should specify the type for value in the implementation of the bar method. Then. if it's anything other than string, the compiler will throw an error.
You can force your TypeScript compiler not to allow any implicit any by adding the following line to your tsconfig.json file.
"noImplicitAny": true
In general, the best practice is to explicitly add the type for function parameters and return values and avoid any to the extent possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With