When TypeScript is compiled with strict null checks, the code snippet below does not pass type checking even though it appears to be correct:
const arr: number[] = [1, 2, 3]
const f = (n: number) => { }
while (arr.length) {
f(arr.pop())
}
The compilation error states:
Argument of type 'number | undefined' is not assignable to parameter of type 'number'. Type 'undefined' is not assignable to type 'number'.
It seems that the compiler fails to recognize that arr.pop()
will always return a number.
This raises some questions:
- Why doesn't the compiler account for this scenario? Is incorporating more advanced null-checking in such cases challenging, or is it a feature that the TypeScript team has yet to implement?
- What is the most conventional way to write the above code while ensuring it passes type checking?
To address question 2, one possible solution involves adding an unnecessary check within the loop:
while (arr.length) {
const num = arr.pop()
if (num) { // satisfy the compiler requirement
f(num)
}
}