10

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.

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What happens if you have many methods in the interface? For example: interface I { (name: string): void; (number: number): void; awesomeMethod(): string; }
2

Classes can't have call signatures in TypeScript.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.