Closed
Description
Bug Report
Narrowing of a union type based on generic types does not work correctly in else
branches in TS 4.3.
This likely relates to the changes made in #43183
🔎 Search Terms
generic, narrow, union types, 4.3
🕗 Version & Regression Information
This changed between versions 4.2.3 and 4.3
⏯ Playground Link
💻 Code
function needsToNarrowTheType<First extends { foo: string }, Second extends { bar: string }>(thing: First | Second) {
if (hasAFoo(thing)) {
console.log(thing.foo);
}
else {
// I would expect this to work because the type should be narrowed in this branch to `Second`
console.log(thing.bar); // Error: Property 'bar' does not exist on type 'First | Second'.
}
function hasAFoo(value: First | Second): value is First {
return "foo" in value;
}
}
🙁 Actual behavior
In the else
branch, the type of thing
is First | Second
.
🙂 Expected behavior
In the else
branch. the type of thing
is Second
.