Inject an unnamed function in Typescript

I am trying to implement a function without a name:

interface I {
    (name: string): void;    
}

class C implements I {
    (name: string):void { }
}

I want to use C like this, but it does not work:

C("test");

I can write it in javascript and use the interface declaration: I ("test");

But I want to do the same in Typescript.

+4
source share
2 answers

You cannot do this in classes, but you can do it with a regular function:

interface I {
    (name: string): void;
}

var C: I = function(name: string) {

};

C("test"); // ok
C(1);      // compile error

Then, if you change your interface, you will be notified of a compilation error to change the function C.

+6
source

Classes cannot have call signatures in TypeScript.

+2
source

All Articles