3

I'm studying TypeScript.

I had a question while studying

const arr = [['192.168.0.1', 1234], ['192.168.0.2', 5678], ...];

How do I include different types in a two-dimensional array like the one above?
It would be nice to use 'any', but I don't recommend it in the official documentation.

KimBenGon
  • 315
  • 3
  • 12
  • You want an array of [tuples](https://www.typescriptlang.org/docs/handbook/basic-types.html#tuple) like `Array<[string, number]>`. – jcalz Aug 27 '19 at 01:42
  • Possible duplicate of [Defining array with multiple types in TypeScript](https://stackoverflow.com/questions/29382389/defining-array-with-multiple-types-in-typescript) – Christopher Peisert Aug 27 '19 at 01:47

1 Answers1

7

You can use union types in TypeScript. From the documentation:

A union type describes a value that can be one of several types. We use the vertical bar (|) to separate each type, so number | string | boolean is the type of a value that can be a number, a string, or a boolean.

So, in your case, you can declare the array as:

const arr: Array<(string | number)[]> = [['192.168.0.1', 1234], ['192.168.0.2', 5678], ...];
Nikhil
  • 6,493
  • 10
  • 31
  • 68