将类型参数混合到类的实例类型中



有没有办法让一个基于其属性的具有动态索引结构的类?

我一直在尝试解决这个问题,我能够使用type制作这个索引签名,但我只能实现一个接口。在类/接口中是否有不同的语法,或者这是不可能的?

interface BaseAttributes {
id: string;
}
class One<A extends BaseAttributes> {
//1023: An index signature parameter type must be 'string' or 'number'.
[key: keyof A]: A[key];
constructor(attr: A) {
for(const key in attr) {
this[key] = attr[key]; // I want to type this
}
}
}
interface TwoAttributes extends BaseAttributes{
label: string;
}
class Two extends One<TwoAttributes> {
}

我搞砸了几分钟,找不到任何方法来定义实例类型包含您想要的类型变量的类; 有关原因,请参阅此问题评论。 请注意,即使问题被标记为已修复并且其标题似乎描述了您想要的内容,AFAICT 标题实际上是指作为类型参数的基本构造函数(这是 mixin 类允许的(,而不是包含类型参数的实例类型。

我最接近的是将One类编写为无类型化,然后将其转换为泛型构造函数,以便您可以使用为A指定的任何具体类型对其进行扩展:

interface BaseAttributes {
id: string;
}
class OneUntyped {
constructor(attr: {}) { 
Object.assign(this, attr);
}
}
const One = OneUntyped as {new<A extends BaseAttributes>(attr: A): OneUntyped & A};
interface TwoAttributes extends BaseAttributes{
label: string;
}
class Two extends One<TwoAttributes> {
}
let two: Two;
console.log(two.label);
// Error: Base constructor return type 'OneUntyped & A' is not a class or interface type.
class Three<A extends BaseAttributes> extends One<A> { }

最新更新