Why is it that TypeScript doesn't narrow the type of arrays?
function test(input: (string | number)[]): string[] {
// The type of .map(...) reports that it returns string[].
input = input.map(x => x.toString())
// Type error: Type '(string | number)[]' is not assignable to type 'string[]'.
return input
}
The workaround is not depending on it narrowing the type by just immediately using or assigning to a fresh variable:
function test(input: (string | number)[]): string[] {
return input.map(x => x.toString())
}
function test(input: (string | number)[]): string[] {
const newInput = input.map(x => x.toString())
return newInput
}
I did try casting, but in hindsight that obviously only works on use, e.g. return input as string[]
, and will not narrow the type, as .map(...)
already returns the correctly narrowed type.
It feels counter intuitive to me having to do these workarounds. Why is it that TypeScript cannot narrow this array type and are there better workarounds available?
I did look into the official documentation and looked at similar questions on Stack Overflow, but unless I have overlooked something, I haven't seen this particular question answered with anything else than just to reassign.
It is what I am doing in my own code for now, but I just wish I knew why it is as it is and if I can do better.
> tsc --version
Version 4.2.3