Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing TypeScript interface with bare function signature plus other fields

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.

like image 793
user1147862 Avatar asked May 12 '13 14:05

user1147862


People also ask

Can TypeScript interface have implementation?

Interface as TypeInterface in TypeScript can be used to define a type and also to implement it in the class.

Can we have an interface with optional and default properties in TypeScript?

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!

How do you define a function in interface TypeScript?

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.

Can TypeScript implement multiple interfaces?

Typescript allows an interface to inherit from multiple interfaces.


2 Answers

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; } ); 
like image 160
basarat Avatar answered Oct 20 '22 10:10

basarat


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.

like image 36
Tom Crockett Avatar answered Oct 20 '22 09:10

Tom Crockett