具有动态属性的类的 Typescript 构造函数

时间:2021-03-11 14:07:09

标签: typescript class typescript-generics

类型“typeof Md”不可分配给类型“Model”。 类型 'Md' 不能分配给类型 'Store'。

type Store<T> = {
    [P in keyof T]:T[P]
}

interface Model {
    new <T>(data:T):Store<T>
}

const Md:Model = class<T>  {
    constructor(data:T) {
        Object.assign(this,data)
    }
}

1 个答案:

答案 0 :(得分:0)

Typescript 不理解 Object.assign(this, data) 的含义,所以做这种事情总是需要某种 as 断言。

const Md: Model 表示“我希望此 Md 变量符合 Model 接口。而 const Md = (something) as Model 表示“将(某物)视为 Model 甚至如果不是”。你想要后者。

const Md = class <T> {
  constructor(data: T) {
    Object.assign(this, data)
  }
} as Model;
const obj = new Md({ a: 1, b: 2 });

此实例 obj 的解析类型是

const obj: Store<{
    a: number;
    b: number;
}>

请注意,示例中的 Store<T> 类型与 T 相同。

Typescript Playground Link