I am experiencing an issue with the following code snippet:
let count: number | undefined | null = 10;
count = null;
let result: string | undefined | null = count?.toFixed(2);
console.log(`Result: ${result}`);
The error message I received is as follows:
error TS2339: Property 'toFixed' does not exist on type 'never'.
On the other hand, the following code successfully compiles and outputs to the console as expected:
let count: number | undefined | null = 10;
if (1) {
count = null;
}
let result: string | undefined | null = count?.toFixed(2);
console.log(`Result: ${result}`);
Result: undefined
After analyzing this situation, I realized that in the first example, the compiler incorrectly infers that count
will always be null
. It is interesting to note how the compiler's static analysis lacks consistency, even in cases where the condition of the if
statement is a constant value.
Inquiry
I wonder if there is a specific theoretical or design rationale behind this error message (which may indicate a misunderstanding on my part), or if it was simply a questionable decision to treat this more like a severe error rather than a warning, especially given the limited static analysis capabilities demonstrated in the second example?