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 remend it in the official documentation.
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 remend it in the official documentation.
-
You want an array of tuples like
Array<[string, number]>
. – jcalz Commented Aug 27, 2019 at 1:42 - Possible duplicate of Defining array with multiple types in TypeScript – Christopher Peisert Commented Aug 27, 2019 at 1:47
1 Answer
Reset to default 8You 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], ...];