How do I write a class that implements this TypeScript interface (and keeps the TypeScript compiler happy):
interface MyInterface { (): string; text2(content: string); }
I saw this related answer: How to make a class implement a call signature in Typescript?
But that only works if the interface only has the bare function signature. It doesn't work if you have additional members (such as function text2) to be implemented.
Interface as TypeInterface in TypeScript can be used to define a type and also to implement it in the class.
If you want to set the properties of an interface to have a default value of undefined , you can simply make the properties optional. Copied!
TypeScript Interface can be used to define a function type by ensuring a function signature. We use the optional property using a question mark before the property name colon. This optional property indicates that objects belonging to the Interface may or may not have to define these properties.
Typescript allows an interface to inherit from multiple interfaces.
A class cannot implement everything that is available in a typescript interface. Two prime examples are callable signatures and index operations e.g. : Implement an indexible interface
The reason is that an interface is primarily designed to describe anything that JavaScript objects can do. Therefore it needs to be really robust. A TypeScript class however is designed to represent specifically the prototype inheritance in a more OO conventional / easy to understand / easy to type way.
You can still create an object that follows that interface:
interface MyInterface { (): string; text2(content: string); } var MyType = ((): MyInterface=>{ var x:any = function():string { // Notice the any return "Some string"; // Dummy implementation } x.text2 = function(content:string){ console.log(content); // Dummy implementation } return x; } );
There's an easy and type-safe way to do this with ES6's Object.assign
:
const foo: MyInterface = Object.assign( // Callable signature implementation () => 'hi', { // Additional properties text2(content) { /* ... */ } } )
Intersection types, which I don't think were available in TypeScript when this question was originally asked and answered, are the secret sauce to getting the typing right.
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