Home > Back-end >  How can I write a type for an array with other arrays nested inside it?
How can I write a type for an array with other arrays nested inside it?

Time:12-22

I have the following structure:

[
    [
        [0,0,0],
        [1,1,1],
        [0,0,0],
    ],
        [
        [0,1,0],
        [0,1,0],
        [0,1,0],
    ]
]

How can I avoid this ugly notation? Perhaps by writing types...

allPatterns: number[][][] = [];

CodePudding user response:

For clarity, you could label the inner types:

// Any set of three numbers
type MatrixRow = [number, number, number];
// Any set of three rows
type Matrix = [MatrixRow, MatrixRow, MatrixRow];

const exampleA: Matrix[] = [
    [
        [0,0,0],
        [1,1,1],
        [0,0,0],
    ], [
        [0,1,0],
        [0,1,0],
        [0,1,0],
    ]
];

const exampleB: Matrix[] = [];

You could also create a type for the outer array:

// A list of matrices
type MatrixSet = Matrix[];

const exampleC: MatrixSet = [];

TypeScript playground

CodePudding user response:

I am a noob in TS, but perhaps something like a type that allows nested arrays or numbers.

type DeepArrayOfNumbers = number[] | DeepArrayOfNumbers[];

Then you should be able to support any of your use-cases.


Please feel free to comment/explain if this is a bad pattern or something.

  • Related