我正在try 创建一个包装类.我有一个来自导入包的Base
类,我想用一些日志(log)记录和Try/Catch来包装它,这样Wrapper
类就可以从用户那里完全抽象出来,并且可以像使用Base
类一样使用.到目前为止,我所拥有的是:
class Base {
name: string;
constructor(name: string) {
this.name = name;
}
first() {}
second(val: number) {}
third(vals: number[]) {}
... // a lot of methods, can't map them manually
}
class Wrapper {
bases: Base[] = [];
constructor(names: string[]) {
for (const name of names) {
this.bases.push(new Base(name));
}
}
}
Object.getOwnPropertyNames(Base.prototype).forEach((methodName) => {
if (methodName !== 'constructor') {
Wrapper.prototype[methodName] = function (...args) {
for (const base of this.bases) {
try {
// logging
return base[methodName].apply(base, args);
} catch {}
}
};
}
});
这样做的问题是我收到了一些类型警告:
-
No index signature with a parameter of type 'string' was found on type 'Wrapper'
个 -
No index signature with a parameter of type 'string' was found on type 'Base'
个
忽略这些,包装器类不会继承Base
类型,所以如果我继承了
const wrapper = new Wrapper(['a', 'b', 'c']);
const s = wrapper.first();
我得Property 'first' does not exist on type 'Wrapper'
分.
除了手动重写类型as unknown as Base
之外,还有更好的方法来确保类型安全吗?我可以扩展Base
类,尽管我会丢失一些类属性,比如本例中的name
.
编辑:增加了更多Base
类方法的例子.Base
类非常大,所以有很多不同的方法,包括使用可选参数、重载等