我有一个抽象的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
作为第一个参数?
答案 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
}
}