使用打字稿v1.8.10型後衛下面的代碼是給我一個編譯器錯誤,但我不明白爲什麼要失敗:爲什麼在使用交集類型時,TypeScript類型的警戒器不能正確縮小類型?
export interface MyInterface {
someFunction:() => void;
}
// ExtendedModelType is both a backbone model AND a MyInterface
export type ExtendedModelType = Backbone.Model & MyInterface;
class MyExtendedModelType extends Backbone.Model implements MyInterface {
public someFunction(): void {
let model: ExtendedModelType = new MyExtendedModelType();
if (model instanceof MyExtendedModelType) {
this.functionRequiringConcreteClass(model);
}
}
private functionRequiringConcreteClass(param: MyExtendedModelType) { }
}
編譯器在第13行失敗:
error TS2345: Argument of type 'Model & MyInterface' is not assignable
to parameter of type 'MyExtendedModelType'.
Type 'MyInterface' is not assignable to type 'MyExtendedModelType'.
Property 'functionRequiringConcreteClass' is missing in type 'MyInterface'.
由於交集類型,instanceof檢查應該將'model'變成'Backbone.Model AND MyInterface'。但是,然後將'模型'傳遞給函數會讓編譯器抱怨數據結構。
這是我知道的一些邊緣情況嗎?或者這是一個編譯器錯誤?
C你指向哪裏'export type ExtendedModelType = Backbone.Model&MyInterface;'是你想要做什麼的有效聲明?這看起來像一個二進制和。 –
這是一個交集類型。在因特網上搜索「TypeScript相交類型」 –