javascript - 如何在 TypeScript 中表示包含多种类型的二维数组?

标签 javascript typescript

我正在学习 TypeScript。

我在学习的时候遇到了一个问题

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

如何在像上面那样的二维数组中包含不同的类型?
使用“any”会很好,但我不建议在官方文档中使用它。

最佳答案

您可以在 TypeScript 中使用联合类型。来自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.

因此,在您的情况下,您可以将数组声明为:

const arr: Array<(string | number)[]> = [['192.168.0.1', 1234], ['192.168.0.2', 5678], ...];

关于javascript - 如何在 TypeScript 中表示包含多种类型的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57666656/

相关文章:

javascript - document.getElementById ("<%= errorIcon.ClientID %>");给出 null

javascript - Xpages多次上传删除附件

javascript - 将数字映射到字符

javascript - Meteorjs + Angular 2

javascript - node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10) : 中出现错误

typescript - 需要特定字符串作为 TypeScript 接口(interface)中的可选键

javascript - 仅使用 CSS 在位置之间设置动画?

javascript - AngularJS 中多个指令的一个声明

typescript - 这个 <[T1, T2, T2]> 语法在 TypeScript 中有什么作用?

typescript - 具有未知键的属性的 Io-ts 接口(interface)