Home > database >  Specify the return type of an arrow function in an interface declaration
Specify the return type of an arrow function in an interface declaration

Time:10-17

I want to tell typescript that I'll be using an interface that offers a function named "foo" that always returns a string. The body of the function will be defined by the object implementing the interface.

Something like this :

export interface IMyInterface {
   foo: ():string => void;
}

Unfortunately the compiler says that this :string shouldn't be there. What's the correct syntax? If I remove :string then the function returns type "any" and I don't want to allow that.

CodePudding user response:

The value on the RHS of the arrow is the return type. You're currently saying it is void.

You can also use the alternative syntax (bar below) where the "is a function" status is declared in the name.

interface Example {
    foo: () => string;
    bar(): string;
}

CodePudding user response:

The type of the arrow function comes after =>.

export interface IMyInterface {
   foo: () => string;
}

Playground Link

  • Related