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.
CodePudding user response:
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
}
}
CodePudding user response:
Hope this helps:
function functionName(argumentOne: string, argumentTwo: string, argumentThree: Array<string | number>) {
...
}