1

I am testing Typescript and I ran into troubles with Array, interface and nullable variable :

I have this interface :

interface Entity {
    life: number;
    type: EntityType;
}

And I have this property :

world: Entity[];

I am trying to initialize with :

this.world = [
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null]
];

The compiler told me :

Cannot convert {}[] to Entity[]

Is this possible ? Am I doing something wrong.

Thanks in advance !

PS : Sorry for my english, I am not a native speaker.

1 Answer 1

4

What's happening here is TypeScript is inferring the type of the assignment, and because all the entries in the array are null it's inferring a type of {}[][]. {}[][] isn't assignable to Entity[][] so that's a compile error.

You can make the code compile with a cast type assertion. There's also an error in your code in that you've defined an array of arrays (2D) but world is declared as a 1D array. I assume you intend a 2D array there.

var world: Entity[][];

world = <Entity[][]>[
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null],
    [null, null, null, null, null, null, null, null]
];
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, I understood why the compiler was angry. Thanks for the cast syntax. I didn't know it. Thanks for the 2D Array grammar too. I didn't know this grammar was possible in Typescript.
+1. This is called a "type assertion" in TypeScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.