Bug Report
π Search Terms
narrowing, object type, unknown, unknown narrowing
π Version & Regression Information
- This changed between versions 4.7.x and 4.8.x
- Happens in nightly (4.9.x)
β― Playground Link
Playground link with relevant code
π» Code
const foo = (value: unknown): string => {
if (!value) {
return 'foo';
}
if (value === 'xyz') {
return value; // Type '{}' is not assignable to type 'string'.
}
return '';
};
// This one compiles fine
const bar = (value: unknown): string => {
if (value === 'xyz') {
return value;
}
return '';
};
π Actual behavior
Type '{}' is not assignable to type 'string'.
Even though we've clearly inferred that the unknown is literally the string "xyz", the compiler somehow thinks it is instead {}.
π Expected behavior
Builds fine.
More info
You can see here that its specific to having the false-check at the start of the function.
Removing the if(!value) condition causes the code to compile as expected.
So it seems that turns the value into {} somehow.
Bug Report
π Search Terms
narrowing, object type, unknown, unknown narrowing
π Version & Regression Information
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
Even though we've clearly inferred that the
unknownis literally the string"xyz", the compiler somehow thinks it is instead{}.π Expected behavior
Builds fine.
More info
You can see here that its specific to having the false-check at the start of the function.
Removing the
if(!value)condition causes the code to compile as expected.So it seems that turns the
valueinto{}somehow.