I am currently working on a TypeScript function (still getting acquainted with TS) that accepts a parameter which could be either a number, a string, an array of numbers, or an array of strings.
It is crucial for me to distinguish between these 4 types within my code.
When I use typeof
on an array, it always returns 'object'. How can I differentiate between an array of strings and an array of numbers in my code?
I understand that I could utilize for loops or array methods to determine the type of each element in the array, but I am wondering if there is a more elegant solution.
function numToLet(input: number | number[] | string | string[]) {
if (typeof input === 'number') {
console.log(`The input ${input} is a number.`)
}
if (typeof input === 'string') {
console.log(`The input ${input} is a string.`)
}
if (typeof input === 'object') {
console.log(`The input ${input} is an object. Not sure about its specific type though ¯\_(ツ)_/¯`)
}
}