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

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());

Leave a Comment