在TypeScript接口上声明函数的多种方法:它们有何不同?

时间:2022-07-31 23:56:30

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

我已经看到了以多种方式声明的函数属性,如此TypeScript接口上的func1和func2所示:

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?

这个游乐场链接似乎意味着两者可以互换使用。这有什么限制吗?

1 个解决方案

#1


Is there a difference between the two

这两者之间有区别吗?

Yes.

func: (arg:string) => number;

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:

那是因为它们是类型兼容的。并不意味着它们是同一个东西。请参阅以下属性与方法:

在TypeScript接口上声明函数的多种方法:它们有何不同?

在TypeScript接口上声明函数的多种方法:它们有何不同?

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;
}

#1


Is there a difference between the two

这两者之间有区别吗?

Yes.

func: (arg:string) => number;

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:

那是因为它们是类型兼容的。并不意味着它们是同一个东西。请参阅以下属性与方法:

在TypeScript接口上声明函数的多种方法:它们有何不同?

在TypeScript接口上声明函数的多种方法:它们有何不同?

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;
}