TypeScript - hur man typifierar en flerdimensionell array som har olika former


Jag har en tvådimensionell array som kan ha olika former och kan innehålla antingen siffror eller strängar. Hur kan jag skapa ett gränssnitt för det?

Exempel :

// 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],
]

Svar #1

Om du vill ha en generell typ för 2D-arrayer kan du göra så här:

// 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],
]

Eller som @Nalin Ranjan påpekade kan du göra detta för att representera den specifika typen i ditt exempel:

// 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],
]