typescript 错误 TS2322:类型“Object[]”不可分配给类型“[Object]”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40807744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:29:23  来源:igfitidea点击:

Error TS2322: Type 'Object[]' is not assignable to type '[Object]'

typescriptecmascript-6typescript-typingsdefinitelytyped

提问by Tobias Stangl

I have a code snippet like this:

我有一个这样的代码片段:

export class TagCloud {

    tags: [Tag];
    locations: [Location];

    constructor() {
        this.tags = new Array<Tag>();
        this.locations = new Array<Location>();
    }
}

But this gives me the following errors:

但这给了我以下错误:

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[]'.

错误 TS2322:类型 'Tag[]' 不能分配给类型 '[Tag]'。“标签[]”类型中缺少属性“0”。

错误 TS2322:类型 'Location[]' 不能分配给类型 '[Lo cation]'。“Location[]”类型中缺少属性“0”。

What am I doing wrong (the code is working though)?

我做错了什么(代码正在运行)?

I am using typings with the es6-shim Type descriptions (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/es6-shim).

我正在使用带有 es6-shim 类型描述的类型(https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/es6-shim)。

回答by Nitzan Tomer

In typescript when you declare an array you either do:

在打字稿中,当您声明一个数组时,您可以执行以下操作:

let a: Array<number>;

or

或者

let a: number[];

When you use:

当您使用:

let a: [number];

you are in fact declaring a tuple, in this case of length one with number.
This is another tuple:

您实际上是在声明一个 tuple,在这种情况下,长度为 1 并带有数字。
这是另一个元组:

let a: [number, string, string];

The reason you get this error is because the length of the array you assign to tagsand locationsare 0, and it should be 1.

你得到这个错误的原因是因为数组的长度分配给tagslocations为0,它应该是1。

回答by Jeff

You want to use Tag[]to tell TypeScript you are declaring an array of Tag.

你想用它Tag[]来告诉 TypeScript 你正在声明一个Tag.

export class TagCloud {

    tags: Tag[];
    locations: Location[];

    constructor() {
        // TS already knows the type
        this.tags = []
        this.locations =[]
    }
}