152

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[]>;
3
  • 2
    Please don't use the term typed arrays for this… Commented Apr 18, 2014 at 20:32
  • 1
    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". Commented Apr 20, 2014 at 2:25
  • Thanks, I appreciate the term "strongly typed" :-) Commented Apr 20, 2014 at 14:31

6 Answers 6

223

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

var listOfLists : number[][];
Sign up to request clarification or add additional context in comments.

4 Comments

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][] = []
Is handled differently from the Array<Array<number>> syntax?
52

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

1 Comment

I actually used the any type in Angular, Array<Array<any>>
17

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

Comments

14

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

1 Comment

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

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

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.