错误TS2322:类型“对象[]”是不能分配给输入“[对象]”
问题描述:
我有一段代码是这样的:错误TS2322:类型“对象[]”是不能分配给输入“[对象]”
export class TagCloud {
tags: [Tag];
locations: [Location];
constructor() {
this.tags = new Array<Tag>();
this.locations = new Array<Location>();
}
}
但是这给了我以下错误:
错误TS2322:类型'标签[]'不可分配给类型'[Tag]'。 类型'Tag []'中缺少属性'0'。
错误TS2322:类型'位置[]'不能指定为'[Lo 阳离子]'。 类型'位置[]'中缺少属性'0'。
我在做什么错(代码工作虽然)?
我使用与ES6-垫片类型描述(https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/es6-shim)分型。
答
在打字稿,当你声明数组你要么做:
let a: Array<number>;
或
let a: number[];
当你使用:
let a: [number];
你实际上宣告a tuple在这种情况下,长度为1 w ith号码。
这又是一个元组:
let a: [number, string, string];
你得到这个错误是因为数组的长度分配给tags
和locations
为0,它应该是这个原因1.
答
你想用Tag[]
告诉打字稿您声明的Tag
阵列。
export class TagCloud {
tags: Tag[];
locations: Location[];
constructor() {
// TS already knows the type
this.tags = []
this.locations =[]
}
}