Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I represent a two-dimensional array containing multiple types in TypeScript?

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.

like image 978
KimBenGon Avatar asked Jun 25 '26 02:06

KimBenGon


1 Answers

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], ...];
like image 62
Nikhil Avatar answered Jun 27 '26 14:06

Nikhil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!