【发布时间】:2018-07-28 02:14:23
【问题描述】:
我知道它太通用了,但我希望创建一个类,该类将具有来自通用类型的所有道具和原型,如下所示:
class GenericExtend<T> extends T {
constructor(data: T) {
// here is a workaround to make these 2 classes unique
const proto = { ...GenericExtend.prototype };
Object.assign(proto, Object.getPrototypeOf(data));
Object.setPrototypeOf(this, proto);
Object.assign(this, data);
}
GenericMethod() { }
}
现在,我可以实例化GenericExtend 类,然后像这样获取两个类的类型:
const obj = new GenericExtend<Model>(data);
obj.GenericMethod(); // ok
obj.ModelMethod(); // good!
我的一个解决方案是使用交集,如下所示:
const obj: GenericExtend & Model = new GenericExtend(data) as any;
它有效,但我不太喜欢。有没有更好的办法?
【问题讨论】:
标签: typescript