how to declare member variable as extended type in TypeScript?

和自甴很熟 提交于 2021-01-29 04:13:04

问题


Is there a way to define a "member variable" as an "extension object" instead of a static type (without using an interface)?

Simply something like this pseudocode:

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() {
       }
    }

}

instead of

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

This way I can add properties not defined on the base class or interface without getting type errors, but also get code completion from the base class. Heh, lazy strict typing?


回答1:


Intersection Types

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() {
       }
    }
}



回答2:


Consider a constrained generic type parameter.

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



回答3:


I'm not completely sure that I understand you, but if so then something like this:

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)



来源:https://stackoverflow.com/questions/38985570/how-to-declare-member-variable-as-extended-type-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!