Search code examples
typescripttypescript-typingsstrong-typing

Tyescript: How to define typings for Strongly typed Array of Array


There is already a similar question, only difference is that I want to declare the typings in a d.ts file instead of declaring every time.

I have been writing typings like

interface SomeType {
 key1: string[];
 key2: number;
}

which are Objects with named properties type.


Now I need an Array with two sub-Arrays type,

i.e (something like):

 TheType : [string[], string[]]

So that I can write

let myVar: TheType;

instead of

let myVar: [string[], string[]];

I've Tried to play with namespace, module, declare var with no luck, I can explain the problems with them if required, but I just feel that either I'm missing something very obvious or it's just not possible ?!

Note: workarounds !needed, thanks!


Solution

  • I would mix an interface extending Array with a generic to create a NestedArray type, which you can use with any type. Having a nested array type will make your inline types more readable:

    interface NestedArray<T> extends Array<Array<T>> {}
    
    var x: NestedArray<string> = [['a', 'b'], ['c', 'd'], ['e', 'f']];
    
    var y = x[0]; // y is Array<string>
    var z = x[0][1]; // z is string
    

    Use with other types:

    var x: NestadArray<Customer> = [];