Home > front end >  Typescript annotation question: arrays with key values
Typescript annotation question: arrays with key values

Time:11-02

Does anyone know why this happens according to VSCode?

interface Point {
    x: number;
    y: number;
}

let grid: [key: number, value: [key: number, value: Point]];

// ...

// Gives an object of type  number | [key: number, value: Point]
var col = grid[-5];
// Gives an object of type  number | Point
var pnt = (col as [key: number, value: Point])[-2];

Could anyone explain please?

I want them to not have the number |

CodePudding user response:

This:

let grid: [key: number, value: [key: number, value: Point]];

declares a tuple type: an array with 2 members, where the first is of type number, and the second is another tuple, eg:

[3, [4, somePoint]]

Use an object instead of an array, so that grid[someNum] gives you a column:

let grid: {
    [key: number]: {
        [key: number]: Point;
    };
}

You also might consider using a Map instead of dynamic property names (Maps are better designed for this sort of thing, and you'll occasionally run into issues with those sorts of dynamic property names in TypeScript)

type Col = Map<number, Point>;
const grid = new Map<number, Col>();

CodePudding user response:

The variable let grid is being initialized here:

let grid: [key: number, value: [key: number, value: Point]];

Here 'key' is being set to a number. If you don't want it to return this part, you need to remove the key: number part of the code

  • Related