Home > Blockchain >  Why isn't Typescript inferring this simple type in a conditional?
Why isn't Typescript inferring this simple type in a conditional?

Time:01-05

It infers the type here:

let a: string | undefined;
let b = "";

if(typeof a === "string"){
  b = a
}

But it doesnt here:

let a: string | undefined;
let b: string | undefined;
let c = ""
if(typeof a === "string" || typeof b === "string"){
  c= a || b
}

Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'

Playground

What would be the correct way to write the code here ? Obviously, without unrolling the conditional.

CodePudding user response:

In this case, your code is incorrect and Typescript is correct. If a is the empty string and b is undefined, then the condition is true but c becomes undefined.

I would simply write it as follows:

let a: string | undefined;
let b: string | undefined;
const c = a ?? b ?? "";

Generally speaking Typescript does not work well with disjunctions of constraints, so better to avoid this kind of pattern.

CodePudding user response:

If you pay attention on the code you see that c need to be string and your condition can assign to c the undefined type.

let a: string | undefined;
let b: string | undefined;
let c: string | undefined = ""; // Now this var can be string or undefined

if(typeof a === "string" || typeof b === "string"){
    c = a || b
}
  • Related