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?
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:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With