【问题标题】:Generic Type Error TS2322: Type '{ id: null; }' is not assignable to type 'T'通用类型错误 TS2322:类型 '{ id: null; }' 不可分配给类型 'T'
【发布时间】:2019-01-05 21:37:49
【问题描述】:

我在下面的代码中遇到 TS 类型检查错误。

interface Resource {
  id: string;
}

interface ResourceState<T> {
  data: T;
  hash: string;
}

abstract class ResourceComponent<R extends Resource> {
  protected state: ResourceState<R> = {
    data: { // Type checking KO
      id: ''
    },
    hash: ''
  };
}

// Doesn't suit my use case
// abstract class ResourceComponent<Resource> {
//   protected state: ResourceState<Resource> = {
//     data: {
//       id: null
//     },
//     hash: ''
//   };
// }

interface Model extends Resource {
  name: string;
}

class ModelComponent extends ResourceComponent<Model> {
  constructor() {
    super();
    this.state.data.name = 'ModelComponent'; // Type checking OK
    this.state.data.age = 20; // Type checking OK
    console.log(this.state.data);
  }
}

const component = new ModelComponent();

恰好在第 12 行,我收到错误 TS2322: Type '{ id: null; }' 不可分配给类型 'R'。 TypeScript 不应该明白,因为“R 扩展资源”,数据可以用具有资源类型形状的值初始化。

在第 36、37 行,TS 确实进行了正确的类型检查。

https://stackblitz.com/edit/typescript-rthmqv

【问题讨论】:

  • 您是否启用了--structNullChecks?如果你这样做(并且推荐),那么null 不是字符串。
  • 这与null无关。为了清楚起见,我修改了 sn-p 并添加了一个 stackblitz。谢谢。

标签: typescript


【解决方案1】:

你需要告诉你的数据对象你分配给它的实际上是 R

abstract class ResourceComponent<R extends Resource> {
  protected state: ResourceState<R> = {
    data : { // Type checking KO
      id: "null"
    } as R,
    hash: ''
  };
}

【讨论】:

  • 那行得通。但我希望 TypeScript 能够推断出来。
猜你喜欢
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
  • 2017-04-10
  • 2019-02-07
  • 1970-01-01
  • 2021-11-10
相关资源
最近更新 更多