错误 TS2322:类型 'Object[]' 不可分配给类型“[Object]”
Error TS2322: Type 'Object[]' is not assignable to type '[Object]'
我有这样的代码片段:
export class TagCloud {
tags: [Tag];
locations: [Location];
constructor() {
this.tags = new Array<Tag>();
this.locations = new Array<Location>();
}
}
但这给了我以下错误:
error TS2322: Type 'Tag[]' is not assignable to type '[Tag]'.
Property '0' is missing in type 'Tag[]'.
error TS2322: Type 'Location[]' is not assignable to type '[Lo
cation]'.
Property '0' is missing in type 'Location[]'.
我做错了什么(虽然代码有效)?
我正在使用带有 es6-shim 类型描述的类型 (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/es6-shim)。
您想使用 Tag[]
告诉 TypeScript 您正在声明一个 Tag
的数组。
export class TagCloud {
tags: Tag[];
locations: Location[];
constructor() {
// TS already knows the type
this.tags = []
this.locations =[]
}
}
在打字稿中,当你声明一个数组时,你可以这样做:
let a: Array<number>;
或
let a: number[];
当您使用时:
let a: [number];
你实际上是在声明 a tuple,在这种情况下,长度为 1 和数字。
这是另一个元组:
let a: [number, string, string];
你得到这个错误的原因是因为你分配给tags
和locations
的数组长度是0,应该是1。
我有这样的代码片段:
export class TagCloud {
tags: [Tag];
locations: [Location];
constructor() {
this.tags = new Array<Tag>();
this.locations = new Array<Location>();
}
}
但这给了我以下错误:
error TS2322: Type 'Tag[]' is not assignable to type '[Tag]'. Property '0' is missing in type 'Tag[]'.
error TS2322: Type 'Location[]' is not assignable to type '[Lo cation]'. Property '0' is missing in type 'Location[]'.
我做错了什么(虽然代码有效)?
我正在使用带有 es6-shim 类型描述的类型 (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/es6-shim)。
您想使用 Tag[]
告诉 TypeScript 您正在声明一个 Tag
的数组。
export class TagCloud {
tags: Tag[];
locations: Location[];
constructor() {
// TS already knows the type
this.tags = []
this.locations =[]
}
}
在打字稿中,当你声明一个数组时,你可以这样做:
let a: Array<number>;
或
let a: number[];
当您使用时:
let a: [number];
你实际上是在声明 a tuple,在这种情况下,长度为 1 和数字。
这是另一个元组:
let a: [number, string, string];
你得到这个错误的原因是因为你分配给tags
和locations
的数组长度是0,应该是1。