[英]Difference between fat arrow function and normal function type declarations in TypeScript interfaces
以兩種不同的方式聲明兩個接口,如下所示。 這兩者有區別嗎?
interface IFoo {
onClick: (id: string) => void
}
interface IBar {
onClick(id: string): void
}
與啟用的嚴格 function 類型的類型兼容性存在差異。 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
更嚴格的檢查適用於所有 function 類型,但源自方法或構造函數聲明的類型除外。 專門排除方法以確保泛型類和接口(例如
Array<T>
)繼續大部分協變相關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.