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

Typescript 将类型参数混合到类的实例类型中,typescript,class,Typescript,Class,有没有一种方法可以使类基于其属性具有动态索引结构 我一直在努力解决这个问题,我能够使用类型创建这个索引签名,但我只能实现一个接口。在类/接口中是否有不同的语法,或者只是不可能 interface BaseAttributes { id: string; } class One<A extends BaseAttributes> { //1023: An index signature parameter type must be 'string' or 'numbe

有没有一种方法可以使类基于其属性具有动态索引结构

我一直在努力解决这个问题,我能够使用
类型
创建这个索引签名,但我只能实现一个接口。在类/接口中是否有不同的语法,或者只是不可能

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> {
}
接口基本属性{
id:字符串;
}
一班{
//1023:索引签名参数类型必须为“字符串”或“数字”。
[钥匙:A的钥匙]:A[钥匙];
构造函数(attr:A){
for(属性中的常量键){
this[key]=attr[key];//我想键入这个
}
}
}
接口TwoAttributes扩展了BaseAttributes{
标签:字符串;
}
第二类扩展一类{
}

我把这件事搞砸了几分钟,找不到任何方法来定义一个实例类型包含您想要的类型变量的类;看看原因。注意,尽管问题被标记为“已修复”,其标题似乎描述了您想要的内容,但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> { }
接口基本属性{
id:字符串;
}
第一类非类型{
构造函数(attr:{}){
Object.assign(这个,attr);
}
}
const One=OneUntyped为{new(attr:A):OneUntyped&A};
接口TwoAttributes扩展了BaseAttributes{
标签:字符串;
}
第二类扩展一类{
}
让二:二;
控制台日志(两个标签);
//错误:基构造函数返回类型“OneUntyped&A”不是类或接口类型。
第三类扩展了一个{}

谢谢您的回答。我决定单独编写所有属性,并使用Object.assign方法,因为它感觉更干净,而且当我打开扩展基础的类(
one
)时,我也可以清楚地看到所有属性。