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

时间:2018-01-09 10:58:22

标签: javascript class typescript object mapping

假设我有一个包含一些数据的对象。我想构建一个通用映射器(分别只是一个函数 - 我不想一直实例化一个新类),所有类型都要这样使用: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;
}

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

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

1 个答案:

答案 0 :(得分:2)

您需要将类型构造函数传递给方法。打字稿在运行时删除泛型到T在运行时是未知的。另外,我会强调values一个bti,只允许传递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;
 }

用法:

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)
相关问题