如何在TypeScript中将成员变量声明为扩展类型?

时间:2016-08-16 22:39:19

标签: javascript class inheritance 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;
}

这样我可以在不获取类型错误的情况下添加未在基类或接口上定义的属性,但也可以从基类获取代码完成。嘿, lazy 严格打字?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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() {
       }
    }
}
相关问题