'TypeScript - how to type a multi dimension array that has different shapes

I have a two dimensional array which can have different shapes and can contain either numbers or string. How can I create an interface for that?

Examples:

// example one
[[0]]

// example two
[
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
]

// example three
[
  [0,   'J', 0],
  [0,   'J', 0],
  ['J', 'J', 0],
]


Solution 1:[1]

If you want a general type for 2D arrays you can do this:

// Generic 2D array type
type Arr2DGeneric<T> = T[][];
// The trick is to read this type right to left: An array ([]) of arrays ([]) of type T

// example one
const g1: Arr2DGeneric<number|string> = [[0]]

// example two
const g2: Arr2DGeneric<number|string> = [
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
]

// example three
const g3: Arr2DGeneric<number|string> = [
  [0,   'J', 0],
  [0,   'J', 0],
  ['J', 'J', 0],
]

Or as @Nalin Ranjan pointed out you can do this to represent the specific type in your example:

// Specific to number | string
type NumStrArr2D = (number|string)[][];


// example one
const ns1:NumStrArr2D = [[0]]

// example two
const ns2:NumStrArr2D = [
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
]

// example three
const ns3:NumStrArr2D = [
  [0,   'J', 0],
  [0,   'J', 0],
  ['J', 'J', 0],
]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mattia