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).
This will generate working code, but the compiler will complain that
MyType
is not callable because it has the signaturenew() = 'string'
(even though if you call it withnew
, 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: