我有这个 typescript 类,需要在构造上提供通用类型:

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

最佳答案

一种解决方法是在您的情况下使用<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};
  }
}

09-04 16:34