Reputation: 2016
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
Reputation: 8412
Hope this helps:
function functionName(argumentOne: string, argumentTwo: string, argumentThree: Array<string | number>) {
...
}
Upvotes: 2
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