ChatGPT解决这个技术问题 Extra ChatGPT

Create strongly typed array of arrays in TypeScript

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[]>;
Please don't use the term typed arrays for this…
In TypeScript "typed array" means what it means in most every other programming language except JavaScript, but since they are closely tied together I'll clarify it with "strongly".
Thanks, I appreciate the term "strongly typed" :-)

P
Peter Olson

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

var listOfLists : number[][];

it's not strongly typed though
@PeterOlson is it possible to strongly type if I have array of arrays of such format - [ [string, number], [string, number], ... ] ?
for an array of array of different types var entries: [string, number][] = []
D
Damian Wojakowski

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

I actually used the any type in Angular, Array>
D
DavidRR

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

J
James Harris

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


This seems like it should be a response to that person's comment, instead of a separate answer.
L
LeonardoX

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