2016-04-25 60 views
0

使用打字稿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'。但是,然後將'模型'傳遞給函數會讓編譯器抱怨數據結構。

這是我知道的一些邊緣情況嗎?或者這是一個編譯器錯誤?

+1

C你指向哪裏'export type ExtendedModelType = Backbone.Model&MyInterface;'是你想要做什麼的有效聲明?這看起來像一個二進制和。 –

+0

這是一個交集類型。在因特網上搜索「TypeScript相交類型」 –

回答

1

https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.5

同樣,相交類型具有以下轉讓性關係:

  1. 的交點I型被分配給一個類型T,如果任何類型的I是可分配至T

  2. 如果T可分配給I中的每種類型,則類型T可分配給交點類型I.

所以,根據1,model(I)MyExtendedModelType(T)不得轉讓,因爲沒有任何類型的model(I)是分配給MyExtendedModelType(T)

下面的工作,因爲MyInterface現在分配給MyExtendedModelType(T)(下降private

export interface MyInterface { 
    someFunction:() => void; 
    functionRequiringConcreteClass: (param: MyExtendedModelType) => 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); 
    } 
    } 

    functionRequiringConcreteClass(param: MyExtendedModelType) { } 
} 
相關問題