我正在学习 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/