首页 > 解决方案 > 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”,但是当我调用实例时,它在逻辑上没有显示任何子方法/道具。我正在寻找写一些像“儿童”而不是“任何”这样的想法的可能性——在 TypeScript 中是否有类似的定义?

谢谢你的任何建议。

标签: typescript

解决方案


你可以使用泛型。由于您不能在属性上使用泛型,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>();

推荐阅读