When compiling TypeScript using strict null checks, the following does not type check even though it's fine:
const arr: number[] = [1, 2, 3]
const f = (n: number) => { }
while (arr.length) {
f(arr.pop())
}
The compilation error is:
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 isn't smart enough to know that arr.pop() will definitely return a number.
Some questions:
- Why isn't the compiler smarter? Would adding smarter null-checking for this kind of case be incredibly difficult, or is it something straightforward that the TS team hasn't implemented yet?
- What's the most idiomatic way to write the above that still type-checks?
Re 2, the best I can come up with is to add a superfluous check to the body of the loop:
while (arr.length) {
const num = arr.pop()
if (num) { // make the compiler happy
f(num)
}
}
f(arr.pop() as number)should solve your problem.[email protected]with"awesome-typescript-loader": "^3.2.3", it doesn't have any compiling error.