gpt4 book ai didi

typescript - 在 TypeScript 接口(interface)上声明函数的多种方法 : how are they different?

转载 作者:搜寻专家 更新时间:2023-10-30 21:07:25 24 4
gpt4 key购买 nike

我见过以多种方式声明函数的属性,如此 TypeScript 接口(interface)上的 func1func2 所示:

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

两者有区别吗?有没有一种情况你会使用一个而不是另一个?

This playground link似乎暗示两者可以互换使用。这有什么限制吗?

最佳答案

Is there a difference between the two

是的。

func: (arg:string) => 数字;

这个版本意味着它是一个属性。当您尝试声明 overloads 时,这将限制您。

func2(arg:string): 数字;

这是函数的首选,因为这意味着您可以在事后轻松声明重载(使用接口(interface)的开放性)

seems to imply that the two can be used interchangeably

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

enter image description here

enter image description here

例子

这应该澄清:

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

关于typescript - 在 TypeScript 接口(interface)上声明函数的多种方法 : how are they different?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30179394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com