Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement function without name in Typescript

I'm trying to implement a function without name like this:

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

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

I want to use C like this, but it doesn't 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.

like image 426
Alphapage Avatar asked Jun 05 '15 20:06

Alphapage


2 Answers

You can't do that on 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 by a compile error to change the C function.

like image 134
David Sherret Avatar answered Oct 13 '22 00:10

David Sherret


Classes can't have call signatures in TypeScript.

like image 20
Ryan Cavanaugh Avatar answered Oct 13 '22 01:10

Ryan Cavanaugh