Normally if you try to use a let var without assigning to it first, there's a TS error:
let x: number;
const foo = x; // Variable 'x' is used before being assigned.
But there is no such error if undefined is an acceptable value for that variable:
let x: number | undefined;
const foo = x; // No error.
I want to know if there's a setting or something that will make the second case also error.
The reason: This error is helpful if you're using if/else to set something to one of several values, because it ensures you remembered to assign to it in each branch.
let x: number;
if (blah) {
// do something...
x = something;
} else if (yada) {
// do something else...
x = somethingElse;
} else {
// do a final thing...
// oops, forgot to assing to x here
}
const foo = x; // Error because one of the cases forgot to assign
But if undefined is a valid value, then this doesn't work. Even if undefined is valid, I still want to be forced to explicitly set it to undefined before I use it. Is there any way to accomplish that?
If not, the alternatives I have in mind are:
- Use
nullinstead ofundefined, which only works some of the time, sometimes you really do needundefined. - Use a ternary, but that is only reasonable when the
// do something...parts are very small. - Use an IIFE, which has performance implications and feels messier, but would work.