user1147862 user1147862 - 16 days ago 10
TypeScript Question

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.

Answer

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;
}
);
Comments