TypeScript接口中胖箭函数与普通函数类型声明的区别

问题描述 投票:1回答:1

有两个接口用两种不同的方式声明,如下图。这两者之间有什么区别吗?

interface IFoo {
  onClick: (id: string) => void
}

interface IBar {
  onClick(id: string): void
}

javascript typescript
1个回答
2
投票

在类型兼容性上与 严格的函数类型 启用。功能类型参数位置被检查 反向 (对于 "函数道具")而不是 双向 (对方法)

interface IFooArrow {
  onClick: (id: string) => void
}

interface IBarArrow {
  onClick: (id: 'bar') => void
}

declare let fooA: IFooArrow;
declare let barA: IBarArrow;

fooA = barA; // error: Type 'string' is not assignable to type '"bar"'

interface IFooMethod {
  onClick(id: string): void
}

interface IBarMethod {
  onClick(id: 'bar'): void
}

declare let fooM: IFooMethod;
declare let barM: IBarMethod;

fooM = barM; // no error

更严格的检查适用于所有函数类型,除了那些源于 办法 或构造函数声明。方法 被特别排除在外,以确保通用类和接口(如 Array<T>)继续多为共变关系。

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.