打字稿:如何将对象映射到类型?

san*_*oco 7 javascript mapping class object typescript

假设我有一个包含一些数据的对象。我想为所有类型构建一个通用映射器(分别只有一个函数 - 我不想一直实例化一个新类),以便像这样使用:this.responseMapper.map<CommentDTO>(data);

它应该简单地从给定类型中获取所有属性并将数据映射到它。到目前为止我尝试过的:

public map<T>(values: any): T {
    const instance = new T();

    return Object.keys(instance).reduce((acc, key) => {
        acc[key] = values[key];
        return acc;
    }, {}) as T;
}
Run Code Online (Sandbox Code Playgroud)

new T(); 会抛出错误: 'T' only refers to a type, but is being used as a value here.

这样做的正确方法是什么?

Tit*_*mir 6

您需要将类型构造函数传递给该方法。Typescript 在运行时擦除泛型到在运行时T未知。此外,我会收紧valuesbti 以只允许T传入成员。 这可以通过Partial<T>

public map<T>(values: Partial<T>, ctor: new () => T): T {
    const instance = new ctor();

    return Object.keys(instance).reduce((acc, key) => {
        acc[key] = values[key];
        return acc;
    }, {}) as T;
 }
Run Code Online (Sandbox Code Playgroud)

用法:

class Data {
    x: number = 0; // If we don't initialize the function will not work as keys will not return x
}

mapper.map({ x: 0 }, Data)
Run Code Online (Sandbox Code Playgroud)