简体   繁体   English

TypeScript 接口中的粗箭头 function 和普通 function 类型声明之间的区别

[英]Difference between fat arrow function and normal function type declarations in TypeScript interfaces

Having two interfaces declared in two different ways as below.以两种不同的方式声明两个接口,如下所示。 Is there a difference between those two?这两者有区别吗?

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

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

There's a difference in type compatibility with strict function types enabled.与启用的严格 function 类型的类型兼容性存在差异。 Function type parameter positions are checked contravariantly (for "function prop") instead of bivariantly (for method) Function类型参数位置以逆变方式(对于“函数道具”)而不是双变量方式(对于方法)进行检查

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

The stricter checking applies to all function types, except those originating in method or constructor declarations.更严格的检查适用于所有 function 类型,但源自方法或构造函数声明的类型除外。 Methods are excluded specifically to ensure generic classes and interfaces (such as Array<T> ) continue to mostly relate covariantly.专门排除方法以确保泛型类和接口(例如Array<T> )继续大部分协变相关。

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM