0

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.

1
  • 2
    Array<string | number> Commented Nov 25, 2022 at 8:50

2 Answers 2

5

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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Hope this helps:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.