2

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],
]
2
  • 2
    How about type TwoDimensional = (string | number)[][];? Commented Mar 10, 2022 at 10:50
  • This worked but for a full reveal the examples above are part of an object with other properties so in my case I needed to do a bit more to get rid of some typescript errors but this does the trick. Commented Mar 10, 2022 at 12:10

1 Answer 1

3

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],
]
Sign up to request clarification or add additional context in comments.

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.