Typescript – How to make a class implement a call signature in Typescript

typescript

I have defined the following interface in typescript:

interface MyInterface {
    () : string;
}

This interface simply introduces a call signature that takes no parameters and returns a string. How do I implement this type in a class? I have tried the following:

class MyType implements MyInterface {
    function () : string {
        return "Hello World.";
    }
}

The compiler keeps telling me that

Class 'MyType' declares interface 'MyInterface' but does not implement it: Type 'MyInterface' requires a call signature, but Type 'MyType' lacks one

How can I implement the call signature?

Best Answer

Classes can't match that interface. The closest you can get, I think is this class, which will generate code that functionally matches the interface (but not according to the compiler).

class MyType implements MyInterface {
  constructor {
    return "Hello";
  }
}
alert(MyType());

This will generate working code, but the compiler will complain that MyType is not callable because it has the signature new() = 'string' (even though if you call it with new, it will return an object).

To create something that actally matches the interface without the compiler complaining, you'll have to do something like this:

var MyType = (() : MyInterface => {
  return function() { 
    return "Hello"; 
  }
})();
alert(MyType());