-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Closed
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue
Milestone
Description
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.
Metadata
Metadata
Assignees
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue