Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a Typescript class interface does not preserve method types

Tags:

typescript

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.

like image 270
Danny Delott Avatar asked Jun 20 '26 04:06

Danny Delott


2 Answers

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.

like image 114
basarat Avatar answered Jun 21 '26 18:06

basarat


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.

like image 42
Behrooz Avatar answered Jun 21 '26 18:06

Behrooz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!