Lokomotywa
Lokomotywa

Reputation: 2844

Define Method Signature that takes a function as parameter

I want to declare a Type Definition that this function obeys:

var a : MyInterface = function(func : <T>(t: T) => number) {
  console.log("do Nothing");
  return func(123) + " someString";
}

What I am trying, is to build an Interface that takes a function f returning a number as parameter and returning a string itself. To my understanding, the Interface should look like this.

interface MyInterface {

    (func: (<T>(t: T) => number)) => string;
}

But it does not work, complaining about the final '=>', saying ':' expected.

If I simply ommit the return type 'string', the compiler is happy. What can I do about that?

Upvotes: 0

Views: 33

Answers (1)

Tao
Tao

Reputation: 2242

In an interface the return type of a callable signature uses : instead of =>. So in your case it would be

interface MyInterface {
    (func: (<T>(t: T) => number)): string;
}

But if you only want to declare a function type it would be more straightforward to use the shorthand syntax which again uses =>.

type MyFunction = (func: (<T>(t: T) => number)) => string

The advantage of the former syntax is that it lets you define overload signatures and hybrid types that are not only callable but also have properties.

Upvotes: 2

Related Questions