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

how to declare member variable as extended type in TypeScript?

本文关键字:变量 扩展 类型 成员 声明 TypeScript      更新时间:2023-09-26

是否有办法将"成员变量"定义为"扩展对象"而不是静态类型(不使用接口)?

就像这样的伪代码:

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;
}

这样,我可以添加没有在基类或接口上定义的属性而不会出现类型错误,而且还可以从基类获得代码完成。嘿,懒惰严格类型?

交集类型

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

考虑一个受约束的泛型类型参数

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

我不确定我是否完全理解你的意思,但如果是的话,那么像这样:

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)