【问题标题】:Typescript: How to get subclass instance using parent get method打字稿:如何使用父get方法获取子类实例
【发布时间】:2019-02-14 09:14:37
【问题描述】:

假设我有一个带有返回实例的静态方法的父类,

abstract class AbstractManager {
    private static instance: AbstractManager;

    constructor() {
        AbstractManager.instance = this;
    }

    public static getInstance(): AbstractManager {
        return this.instance
    }

}

我有一个扩展父类的子类,

class Manager extends AbstractManager {
    constructor() {
        super();
    }
}

如果我调用 Manager.getInstance(),则返回类型是父 AbstractManager

有没有办法设置父 getInstance() 方法,以便它返回子类型?

显然,我可以为每个返回或强制转换为子类型的子类添加 getInstance(),但如果我有 100 个子类,那么我需要编写该方法 100 次。

虽然我对泛型的了解有限,但我尝试使用泛型的另一个解决方案是,

public static getInstance<T extends AbstractManager>(): T {
    return this.instance;
}

但这导致了错误Type 'AbstractManager' is not assignable to type 'T'.

是否可以这样设置

Manager.getInstance() // is of type Manager not AbstractManager.

或者我应该以不同的方式解决这个问题吗?谢谢。

【问题讨论】:

    标签: typescript instance subclass


    【解决方案1】:

    您的getInstance 方法是AbstractManager 类的静态方法,它对实例化的类没有任何作用。删除static

    您也不需要instance 成员。

    abstract class AbstractManager {
    
        constructor() {
        }
    
        public getInstance(): this {
            return this
        }
    
    }
    
    class Manager extends AbstractManager {
        managerTalk() {
            console.log("Hello I am Manager");
        }
        constructor() {
            super();
        }
    }
    
    const manager = new Manager();
    
    const instance = manager.getInstance();
    console.log(manager.getInstance()) // <--Manager
    
    manager.managerTalk();
    instance.managerTalk();
    

    看看Typescript Playground

    【讨论】:

    • 您好,感谢您的回复,静态方法的重点是我可以检索该类的相同实例。在您的解决方案中,manager.getInstance() 方法的返回类型仍然为 AbstractManager,而不是 Visual Studio 代码中的子类型 Manager
    • @aXises 不,不是。看看我更新的答案中的链接。
    • 向子类添加任何实例方法,打字稿游乐场也将显示错误,指出该属性在类型 AbstractManager 上不存在。由于游乐场链接不适合此处,我已截取了屏幕截图。 Image
    • @aXises 那是我的错,我忘记从 getInstance 的返回类型中删除 AbstractManager 给 Typescript 的类型错误(但这只是一个编译问题)。答案已更新。
    • 很好,将返回类型设置为this 也可以。是否可以设置一种可以从静态上下文调用它的方式?这样就可以使用静态getInstance() 方法来使用和检索相同的实例。
    猜你喜欢
    • 2017-02-25
    • 2021-06-16
    • 2021-08-28
    • 2020-06-03
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    相关资源
    最近更新 更多