The following doesn't compile:
function returnString(): string {
const s = Math.random() < 0.5 ? 'hey' : null;
const sIsString = s !== null;
if (sIsString) {
return s; // <-- problematic line
}
return 'hey';
}
Error: Type '"hey" | null' is not assignable to type 'string'.
Type '"hey" | null' is not assignable to type 'string'.
It does compile when the comparison happens inside the conditional:
function returnString(): string {
const s = Math.random() < 0.5 ? 'hey' : null;
if (s !== null) {
return s;
}
return 'hey';
}
Why does placing the type check inside a variable make a difference to the compiler?
The mechanism that can narrow down union type variables like s
is called control flow analysis , but it only happens on a per-variable basis.
The compiler cannot make a connection between your correlated variables s
and sIsString
. So if sIsString
is true
, you know that s !== null
, but TS doesn't. It just looks at s
and sIsString
, as if they were completely independent.
The second case works, because you perform the type guard check directly on the variable s
and as said control flow analysis works per variable. So its union type string | null
string | null
can properly narrowed down to string
after the s !== null
type check.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.