Create strongly typed array of arrays in TypeScript

Typescript

Typescript Problem Overview


In a language like C# I can declare a list of lists like:

List<List<int>> list_of_lists;

Is there a similar way to declare a strongly typed array of arrays in TypeScript? I tried the following approaches but neither compiles.

var list_of_lists:int[][];
var list_of_lists:Array<int[]>;

Typescript Solutions


Solution 1 - Typescript

int is not a type in TypeScript. You probably want to use number:

var listOfLists : number[][];

Solution 2 - Typescript

You do it exactly like in Java/C#, e.g. (in a class):

class SomeClass {
    public someVariable: Array<Array<AnyTypeYouWant>>;
}

Or as a standalone variable:

var someOtherVariable: Array<Array<AnyTypeYouWant>>;

Solution 3 - Typescript

The simplest is:

x: Array<Array<Any>>

And, if you need something more complex, you can do something like this:

y: Array<Array<{z:int, w:string, r:Time}>>

Solution 4 - Typescript

@Eugene you can use something like Array<Array<[string, number]>> to define a Map type

Solution 5 - Typescript

You can create your own custom types to create a strongly typed array:

type GridRow = GridCell[]   //array of cells
const grid: GridRow[] = []; //array of rows

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsilentorbView Question on Stackoverflow
Solution 1 - TypescriptPeter OlsonView Answer on Stackoverflow
Solution 2 - TypescriptDamian WojakowskiView Answer on Stackoverflow
Solution 3 - TypescriptI'mView Answer on Stackoverflow
Solution 4 - TypescriptJames HarrisView Answer on Stackoverflow
Solution 5 - TypescriptLeonardoXView Answer on Stackoverflow