I have a piece of code where I need to know in a few different places whether or not a variable is an array (it can be an array or string). If it is, I map over the data. If not, I do something else.
Simplified code, which typescript complains about:
function myFunc(input: unknown[] | string) {
const isArray = Array.isArray(input);
if (isArray) {
// this line throws an error, since `map` is not a valid method for strings
return input.map(/* do stuff here*/);
}
return input;
}
If I change the line with the if statement to this:
if (Array.isArray(input))
then typescript seems to understand that input is in fact an array.
I use that check in several places in the real code though, and would like to use a single variable for readability, rather than doing Array.isArray every time.
What's going on here?