2016-08-16 148 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() { 
     } 
    } 
}