#Can I make "undefined"-able vars still need to be initialized before use?

5 messages · Page 1 of 1 (latest)

glossy spade
#

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:

  1. Use null instead of undefined, which only works some of the time, sometimes you really do need undefined.
  2. Use a ternary, but that is only reasonable when the // do something... parts are very small.
  3. Use an IIFE, which has performance implications and feels messier, but would work.
tulip pike
#

@glossy spade Technically, it looks like this works;

#
function foo(bool: boolean) {
  let x: number | undefined;
  if(bool) {
    x = 0;
  } else {
    x = 1;
  }
  const y: number = x;
  return y;
}
#

But I would mostly do either #2, a ternary, or make a function. IIFEs are ugly, but pulling out non-trivial logic into a named function is good.

glossy spade
#

Oh, reassigning to a const is clever, thanks! I also think you're right that in most cases where the "something else" is not small, a separate named function is not a bad way to go.