Closed
Description
TypeScript Version: 3.4.3
Search Terms:
user-defined type guard, condition, inference, narrow, control-flow
Code
type A = {
type: 'A',
aProp: 42
}
type B = {
type: 'B',
bProp: 42
}
type AorB = A | B
function isAorB(obj: unknown): obj is AorB {
return true
}
// Does not work if narrowed with if/else
let x: any
if (isAorB(x)) {
if (x.type === 'A') {
x.aProp // ERROR (x still AorB)
} else {
x.bProp // ERROR (x still AorB)
}
}
// Curriously works with switch/case
if (isAorB(x)) {
switch (x.type) {
case 'A':
x.aProp // WORKS (x is A)
break;
default:
x.bProp // WORKS (x is B)
}
}
Expected behavior:
After passing User-Defined Type Guard, it should be possible to narrow this type using classical control flow.
Actual behavior:
After passing a User-Defined Type Guard, it's not possible to narrow using if/else control flow.
It works with switch/case though.
Playground Link:
Related Issues:
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
jack-williams commentedon May 15, 2019
Duplicate of #30557
typescript-bot commentedon May 19, 2019
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.