【发布时间】: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 确实进行了正确的类型检查。
【问题讨论】:
-
您是否启用了
--structNullChecks?如果你这样做(并且推荐),那么null不是字符串。 -
这与null无关。为了清楚起见,我修改了 sn-p 并添加了一个 stackblitz。谢谢。
标签: typescript