2016-08-16 66 views
0

有沒有辦法將「成員變量」定義爲「擴展對象」而不是靜態類型(不使用接口)?如何在TypeScript中將成員變量聲明爲擴展類型?

只要是這樣的僞代碼:

class Foo { 

    bar -> extends Rectangle; 
    constructor(barInstance:IRectangle){ 
     this.bar = barInstance; 

     this.bar.getArea(); //<-- is code completed because interface IRectangle 

     // no type error 
     this.bar.someCustomFunction = function() { 
     } 
    } 

} 

,而不是

class Foo { 
    bar: IRectangle; 
    //or 
    bar:Rectangle; 
} 

這樣我可以添加在基類或接口沒有得到錯誤類型不定義的屬性,而且還可以獲得代碼完成來自基類。嘿,懶惰嚴格打字?

回答

0

考慮受約束的泛型類型參數。

interface Base { 
    prop: number; 
} 

interface Child extends Base { 
    thing: string; 
} 

class Foo<T extends Base> { 
    bar: T 
} 

var foo = new Foo<Child>(); 
foo.bar.thing; // now permitted by the type checker 
+0

我想做到這一點,而不必明確定義'東西',但動態分配它而不會引發類型錯誤,但也可以得到代碼提示...有點像this.bar.thing =()=> {return true;}本質上,鍵入到 FlavorScape

+0

如果您讓您的類將泛型類型的實例作爲構造函數參數,您可以編寫例如一個對象文字,並且可以推斷它的類型。我不確定在實例化之後分配新屬性併爲它們進行類型檢查有解決方案。這些模式傾向於混淆靜態分析。 –

+0

如果以後確實需要添加其他屬性,我會讓它們成爲指定接口的可選成員。 –

0

我不能完全肯定,我理解你,但如果這樣的話是這樣的:

interface IRectangle { 
    getArea(): void; 
} 

class Rectangle implements IRectangle { 
    getArea(): void {} 
    someCustomFunction(): void {} 
} 

class Foo<T extends IRectangle> { 
    bar: T; 

    constructor(barInstance: T){ 
     this.bar = barInstance; 
     this.bar.getArea(); 

     // no type error 
     if (this.bar instanceof Rectangle) { 
      (this.bar as any as Rectangle).someCustomFunction = function() {} 
     } 
    } 
} 

code in playground

0

交會類型

interface IRectangle { 
    getArea:() => number; 
} 

class Foo { 
    bar: IRectangle & { [key: string]: any; }; 

    constructor(barInstance:IRectangle){ 
     this.bar = barInstance; 

     this.bar.getArea(); //<-- is code completed because interface IRectangle 

     // no type error 
     this.bar.someCustomFunction = function() { 
     } 
    } 
} 
相關問題