【问题标题】:How to declare an array with more than one type in TypeScript?如何在 TypeScript 中声明具有多种类型的数组?
【发布时间】:2022-11-25 17:07:24
【问题描述】:

我正在编写一个函数,其中一个参数是一个可以包含字符串或数字的数组:

function functionName(argumentOne: string, argumentTwo: string, argumentThree: string[] | number[]) {
  ...
}

argumentThree的一个实例:["string1", 2, "string3"]

string[] 是一个字符串数组,number[] 是一个数字数组。因此我的代码给我一个错误。

【问题讨论】:

  • 数组<字符串 |号码>

标签: typescript


【解决方案1】:

您可以为此使用联合类型:

//        alternatively: Array<string | number>
function myFunction(arr: (string | number)[]) {
  for (const element of arr) {
    // typeof element => string | number
  }
}

【讨论】:

    【解决方案2】:

    希望这可以帮助:

    function functionName(argumentOne: string, argumentTwo: string, argumentThree: Array<string | number>) {
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-20
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 2021-07-27
      • 2018-08-23
      • 2019-12-29
      • 2021-11-06
      相关资源
      最近更新 更多