Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple ways to declare a function on a TypeScript interface: how are they different?

Tags:

typescript

I've seen properties that are functions declared in multiple ways, as illustrated by func1 and func2 on this TypeScript interface:

interface Thing {
    func: (arg:string) => number;
    func2(arg:string): number;
}

Is there a difference between the two? Is there a case in which you would use one over the other?

This playground link seems to imply that the two can be used interchangeably. Are there any limits to this?

like image 589
martiansnoop Avatar asked May 11 '15 23:05

martiansnoop


1 Answers

Is there a difference between the two

Yes.

func: (arg:string) => number;

This version means its a property. This will limit you when you try to declare overloads.

func2(arg:string): number;

This is preferred for functions as this means that you can easily declare overloads after the fact (using the open ended nature of interfaces)

seems to imply that the two can be used interchangeably

That is because they are type compatible. Does not mean that they are the same thing. See property vs. method below:

enter image description here

enter image description here

Example

This should clarify :

interface Thing {
    func: (arg: string) => number;
    func2(arg:string): number;
}

interface Thing {
    // Overload not permitted
    func: (arg: number) => string; // ERROR!
    // Overload okay 
    func2(arg: number): string;
}
like image 183
basarat Avatar answered Oct 22 '22 14:10

basarat