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

Tobias Stangl picture Tobias Stangl · Nov 25, 2016 · Viewed 44.9k times · Source

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

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).

Answer

Nitzan Tomer picture Nitzan Tomer · Nov 25, 2016

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:

let a: [number, string, string];

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