Description
TypeScript Version: 3.5.1
Search Terms: void typeof undefined narrow use before assign
Code
// with strictNullChecks
const x2: void = undefined;
const x3: void = undefined;
if(typeof x2 === "undefined") {
x2 // Error: Variable 'x2' is used before being assigned.
}
if(typeof x3 !== "undefined") {
x3 // never. x3 should probably be void
}
// without strictNullChecks
const x2: void = undefined;
if(typeof x2 === "undefined") {
x2 // x2 remains void here, not undefined.
}
if(typeof x2 !== "undefined" && x2 !== null) {
x2 // x2 remains void here, rather than never.
}
Expected behavior:
Using x2
inside the first conditional in the strictNullChecks
example should not error, as the variable absolutely was assigned to before use (whatever its type should be).
Also, the semantics around narrowing void
should be consistent when strictNullChecks
is on and when it's off. And, based on some of the comments I've seen about void
's purpose, it seems like the semantics with strictNullChecks off are the right ones.
Actual behavior:
The use of x2
triggers an error, as mentioned.
And narrowing void
is a no-op when strictNullChecks
is disabled (i.e., it always results in void
), whereas narrowing void
can produce never
when strictNullChecks
is enabled.
Playground Link:
With strictNullChecks: https://www.typescriptlang.org/play/index.html#code/PTAEHcEsBcAtQM7QE6QMbQHIFcA2uBhWAUzQGsEAoNAewDslQAPAJgC5QA3GyAE1AC8obHV7EAZpDrFeAbmr1GTAMwdufQcNESpM+ZUjiAFNACeAB2I1xzFoIFCARCLGTpvRwEpQAb0qgA21AQUABRZGQaZA4ANQBDVDiAI1xiUAByVnTQSARhBBlQJIkotOKpAHNQOIQESAr3ADpKAF9KA2MzS2tmZVAAQgdQZ203GS9ff0CVYLBpTmJkVqA