typescript - Typescript 中 ()=>any 和 {():any} 有什么区别
问题描述
现在这段代码没有错误,Typescript 编译器认为它是完全有效的,但它们是否相同?有人可以解释这两种类型定义之间的区别,并为它们中的每一种都提供很好的用例示例。
const b = () =>'hello'
const x: ()=>string = b
const y: {():string} = b
解决方案
他们是一样的。
如果需要,第二种形式确实为您提供了添加其他静态属性的选项。
type FunctionWithId = {
(): string;
id: number;
}
const b = () => 'hello'
b.id = 4;
const x: FunctionWithId = b
也可以使用第二个版本进行函数重载:
type Example = {
(x: number): number;
(x: string): string;
}
因此,如果您需要其中一些额外功能,请使用第二种语法。如果不是,也可以,而且您可能会更频繁地看到第一个,因为它更简单。
推荐阅读
- windows - 将 Ferdi 的紫色 (#7266f0) 颜色更改为黄色 (#edd75a)
- r - r中的gather()函数在存在时找不到我的列
- gradle - jar 执行缺少类:NoClassDefFoundError
- python - 如何使用 seleinum 点击某物?javascript:void(0) 蟒蛇
- python - 在 Pandas 中具有重复索引且没有聚合函数的数据透视表
- java - 使用java从路径创建JSON
- sql - 存储过程参数检查非空字符串
- azure - 尝试向 Azure 订阅添加其他所有者时的奇怪现象
- swift - 使用 Charts API Swift 显示时间戳
- angular - RouterModule.forRoot() 再次调用了两次