将类型添加到TypeScript中继承类的未知函数名称中

时间:2019-04-27 07:47:44

标签: typescript

我有一个抽象的Lock类,它继承了MorticeLock类。 MorticeLock可以决定如何命名其公共方法,但应遵循一定的指导原则:第一个参数始终必须是名为string的{​​{1}}。

key

如何强制继承abstract class Lock { // ["any public method"]: (key: string ...args: any[]): => LockResult; } class MorticeLock extends Lock { public unlock(key: string, options: object): LockResult; } class AnyLock extends Lock { public crack(key: string, material: object, options: object): LockResult; } 的类的任何公共方法始终使用Lock作为第一个参数?

1 个答案:

答案 0 :(得分:1)

在TypeScript中无法做到这一点。

如果您被限制使用类,那么 可以做的就是添加另一层间接寻址-尽管这不会强制返回类型。

abstract class Lock<T> {
    private readonly viewCache: Record<string, T> = {};

    protected abstract createViewImpl (key: string): T;

    public createView (key: string): T {
        if (!Object.prototype.hasOwnProperty.call(this.viewCache, key)) {
            this.viewCache[key] = this.createViewImpl(key);
        }
        return this.viewCache[key];
    }
}

class MorticeLock extends Lock<MorticeLockView> {
    protected createViewImpl (key: string): MorticeLockView {
        return new MorticeLockView(key, this);
    }
}

class MorticeLockView {
    private readonly key: string;
    private readonly lock: MorticeLock;

    public constructor (key: string, lock: MorticeLock) {
        this.key = key;
        this.lock = lock;
    }

    public unlock (options: object): LockResult {
        // We now have access to the key and the lock object, but no longer have to
        // enforce the first parameter being a string
    }
}
相关问题