![](/img/trans.png)
[英]error TS2322: Type 'string | null' is not assignable to type 'number'
[英]Generic Type Error TS2322: Type '{ id: null; }' is not assignable to type 'T'
我在下面的代码中收到 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 正确地进行了类型检查。
你需要告诉你的数据对象你分配给它的实际上是 R
abstract class ResourceComponent<R extends Resource> {
protected state: ResourceState<R> = {
data : { // Type checking KO
id: "null"
} as R,
hash: ''
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.