To troubleshoot this issue, you can follow the steps below:
function test(x: string | undefined, y: string | undefined) {
type X1 = typeof x; // string | undefined
type Y1 = typeof y; // string | undefined
if (x || y) {
type X2 = typeof x; // string | undefined
type Y2 = typeof y; // string | undefined
if (x) {
type X3 = typeof x; // string
type Y3 = typeof y; // string | undefined
const a = x.length
} else {
type X4 = typeof x; // string | undefined
type Y4 = typeof y; // string | undefined
const b = y.length
}
}
}
In essence, (x || y)
is unable to narrow down the types.
The conditional flow analysis checks for !== undefined
and !== null
conditions (a documented limitation of TS), so it's recommended to rewrite it like this:
function test(a: string | undefined, b: string | undefined) {
if (a !== undefined ) {
const aLength = a.length; // number
} else if(b !== undefined){
const bLength = b.length; // number
}
}