TypeScript-返回父类中子对象的类型? (单例的类型)

时间:2019-04-16 08:05:08

标签: typescript

我有以下问题。 在打字稿中,我为单例创建了抽象类,但是我正在寻找正确的响应类型。


abstract class Singleton {
    private static _instance: any;
    static get instance(): any {
        if (!this._instance) {
            var me: any = this;
            this._instance = new me();
        }

        return this._instance;
    }
}

class Test extends Singleton {
    public test(): string {
        return "hello world";
    }
}

var testInstance = Test.instance;
// then testInstance dont support intellisence of supported methods

实际上我使用了“ any”,但是当我调用instance时,它在逻辑上没有显示任何child方法/ props。 我正在寻找写“儿童”之类的东西而不是“任何”的可能性-像TypeScript这样的定义是否可能?

谢谢您的建议。

2 个答案:

答案 0 :(得分:0)

您可以使用泛型。由于无法在属性get instance()上使用泛型,因此变成getInstance()

abstract class Singleton {
    private static _instance: any;

    static getInstance<T>(): T{
        if (!this._instance) {
            var me: any = this;
            this._instance = new me();
        }

        return this._instance as T;
    }
}

class Test extends Singleton {
    public test(): string {
        return "hello world";
    }
}

var testInstance = Test.getInstance<Test>();

答案 1 :(得分:0)

基于此thread的Ryan回答。您可以按照他介绍的模式写这样的

dockerstartup.sh

playground