这段代码在vanilla javascript中运行良好。
const enhancementA = {
a() {
return this.c + 1;
},
};
const enhancementB = {
b() {
return this.c + 2;
},
};
class C {
c = 0;
constructor() {
Object.assign(this, enhancementA, enhancementB);
}
}
const d = new C();
d.a() // 1
d.b() // 2
d.c // 0但它在typescript中不起作用
d.a() // TS2339: Property 'a' does not exist on type 'C'.
d.b() // TS2339: Property 'b' does not exist on type 'C'.我如何让它在typescript中工作?
发布于 2021-02-25 00:16:31
我不认为C类可以保持原样,因为动态添加了enhancementA和enhancementB,它们不存在于C中,因此不能从构造函数返回(或者突变为支持类型的实例)。我会创建一个函数,返回一个结合了增强功能的对象。
类型参数可用于指示this必须是具有数字c属性的对象。
const enhancementA = {
a<T extends { c: number }>(this: T) {
return this.c + 1;
},
};
const enhancementB = {
b<T extends { c: number }>(this: T) {
return this.c + 2;
},
};
const makeC = () => {
return {
c: 0,
...enhancementA,
...enhancementB
};
};
const d = makeC();
d.a() // 1
d.b() // 2
d.c // 0这将生成一个类型为
{
b<T extends { c: number; }>(this: T): number;
a<T extends { c: number; }>(this: T): number;
c: number;
}https://stackoverflow.com/questions/66354580
复制相似问题