2

Is it possible to define a function interface in typescript?

for instance, when we have things such as

meth (a : {b: B, c: C}) : {b: B, c: C} {...}

we can write

interface A {
    b : B;
    c : C;
}
meth (a : A) : A {...}

however, when we have something like

meth (a : (b: B) => C) : (b: B) => C {...}

can we do something similar, like define a function type so that we can write

meth (a : A) : A {...}

again?

1 Answer 1

1

Interfaces support call signatures. Actually the syntax you use can be seen a shorthand for the more verbose full syntax:

interface A 
{
    (b: B) : C
}
function meth (a : A) : A { return a; }

The interface syntax also has the advantage of supporting multiple overloads for the function :

interface A {
    (b: B): D
    (d: D, b: B): C
}
function meth(a: A) : void
{
    a(new B()); // Call overload with one argument
    a(new D(), new B()); // Call overload with two arguments 
}

meth((b: B | D, d?: D|B) => new D());
Sign up to request clarification or add additional context in comments.

1 Comment

So I'm trying to do overloading with different types: the following does not compile: interface AddSomething { (x: number, y: number): number; (x: string, y: string): string; } const somethingToAdd = (oneString: string, twoString: string): string => { return oneString + twoString; }; function addWrapper( adder: AddSomething, ): void { console.log(adder('hello','world')); } addWrapper(somethingToAdd); When I add a type declaration to the function it says the string types are not compatible with numbers.

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.