构造函数从 Record<string,any> 实例化对象

Constructor instantiate object from a Record<string,any>

我正在尝试创建一个构造函数,该构造函数从类似于 JSON 的参数组装对象,例如:

const inputData: Record<string,any> = {a:1, b:"hello"}

class MyClass {
    a:number;
    b:string;
    
    constructor(data:Record<string,any>){
        for(k in data){
            this[k] = data[k]
        }
    }
}

我不能这样做,因为 k 不是 MyClass 新实例的 'key'。

已经尝试过各种与 typeof keyof 的组合,例如:

constructor(data:Record<string,any>){
    type AllowedKeys = keyof typeof MyClass;
    for(k in data){
        const key:AllowedKeys = k as AllowedKeys;
        this[key] = data[key]
    }
}

但我收到以下错误:

Element implicitly has an 'any' type because expression of type '"prototype"' can't be used to index type 'MyClass'. Property 'prototype' does not exist on type 'MyClass'.(7053)

感谢您的任何建议。

要允许任意键,您可以这样声明您的 class:

class MyClass {
    [index: string]: any; // <-- allow arbitrary keys

    a:number;
    b:string;
    
    constructor(data:Record<string,any>){
        for(k in data){
            this[k] = data[k]
        }
    }
}