最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

Share Improve this question edited Aug 27, 2019 at 1:37 KimBenGon asked Aug 27, 2019 at 1:29 KimBenGonKimBenGon 3155 silver badges12 bronze badges 2
  • 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
Add a ment  | 

1 Answer 1

Reset to default 8

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], ...];
发布评论

评论列表(0)

  1. 暂无评论