我有这个打字稿类需要在构造时提供泛型类型:
type Partial<T> = {
[P in keyof T]?: T[P];
};
class Foo<Bar> {
bis: Partial<Bar> = {}; // (1)
constructor() {
console.log(typeof this.bis); // object
this.bis = {...this.bis}; // (2) Spread types may only be created from object types
}
}
然而,正如您在上面看到的那样,我不会在(1)处收到错误,但我会在(2)处收到错误。
为什么是这样?我该如何解决?
编辑1:
我在Typescript github上打开了issue。
答案 0 :(得分:1)
一种解决方法是在您的情况下使用<object>
,<any>
或<Bar>
显式地转换对象。
我不知道您的要求是否允许但请看一下-
type Partial<T> = {
[P in keyof T]?: T[P];
};
class Foo<Bar> {
bis: Partial<Bar> = {}; // (1)
constructor() {
console.log(typeof this.bis); // object
this.bis = {...<Bar>this.bis};
}
}