Home > other >  Why Typescript doesn't get that at least one variable won't be null?
Why Typescript doesn't get that at least one variable won't be null?

Time:07-01

Given a type SomeType, I have two variables that can be null or of that type. This way:

let a: SomeType|null;
let b: SomeType|null;

Then, if I assign values to both variables (which can be an instance of SomeType or null) and validate them using the following logic, c is still of type SomeType|null.

if (!a && !b) {
  return;
}

const c = a || b;

However, it's sure that c is not null, because of the condition before the assignment.

Casting the variable to the type works, but it looks a bit hacky:

const c = (a || b) as SomeType;

Why TS doesn't get that without the cast? There is a way to make it more obvious for the compiler?

CodePudding user response:

Only individual variables can be narrowed. The sort of dependent relationship between the types of different variables you're looking for isn't something the compiler can do. But in this case, an easy tweak to make things readable without an ugly as is to assign to c in advance, and then check it and return if needed:

const c = a || b;
if (!c) {
  return;
}
// now c will be inferred to be SomeType
  • Related