André
André

Reputation: 2016

How to declare an array with more than one type in TypeScript?

I'm writing a function in which one of the arguments is an array that can have strings or numbers:

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

One instance of argumentThree: ["string1", 2, "string3"]

string[] is an array of strings and number[] is an array of numbers. Therefore my code is giving me an error.

Upvotes: 0

Views: 105

Answers (2)

Ryan Le
Ryan Le

Reputation: 8412

Hope this helps:

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

Upvotes: 2

CollinD
CollinD

Reputation: 7573

You can use a union type for this:

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

Upvotes: 5

Related Questions