Pregunta

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[]>;
¿Fue útil?

Solución

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

var listOfLists : number[][];

Otros consejos

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>>;

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}>>

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

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

It may look odd, but in TypeScript, you can create typed array of arrays, using the following syntax.

For example to create an array of numbers you could write the following:

const numbers: number[] = []; // or more verbose Array<number>

And to create an array of arrays of numbers, you could write the following:

const numbers: number[][] = []; // or more verbose Array<Array<number>>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top