Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 466
Tobias Stangl Avatar asked Nov 25 '16 15:11

Tobias Stangl


People also ask

Is not assignable to type error?

The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.

Is not assignable to type number?

Conclusion # The "Type 'number | undefined' is not assignable to type number" error occurs when a possibly undefined value is assigned to something that expects a number . To solve the error, use the non-null assertion operator or a type guard to verify the value is a number before the assignment.

Is not assignable to parameter of type type unknown?

The error "Argument of type 'unknown' is not assignable to parameter of type" occurs when we try to pass an argument of type unknown to a function that expects a different type. To solve the error, use a type assertion or a type guard when calling the function.

Is not assignable to type response?

The "Type 'void' is not assignable to type" TypeScript error occurs when we forget to return a value from a function, so the function gets an implicit return type of void . To solve the error, make sure you return a value of the correct type from your functions before the assignment.


2 Answers

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.

like image 109
Nitzan Tomer Avatar answered Sep 22 '22 06:09

Nitzan Tomer


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

export class TagCloud {

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

    constructor() {
        // TS already knows the type
        this.tags = []
        this.locations =[]
    }
}
like image 20
Jeff Avatar answered Sep 26 '22 06:09

Jeff