-
Notifications
You must be signed in to change notification settings - Fork 13.1k
Closed
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
TypeScript Version:
3.4.1
Search Terms:
discriminated union, type guard, switch-case, switch, case, if, type narrowing
Code
const BOOLEAN: "BOOLEAN" = "BOOLEAN";
const NUMBERS: "NUMBERS" = "NUMBERS";
type ActionsUnion = { type: typeof NUMBERS; payload: { nums : number[ ] } }
| { type: typeof BOOLEAN; payload: { bool : boolean } };
const typeGuard = (action: any): action is ActionsUnion => true;
const exampleFunction = (action: unknown) => {
if (typeGuard(action)) {
// type narrowing works with switch-case statement
switch (action.type) {
case BOOLEAN:
action.payload.bool; // works
break;
}
// type narrowing does not work with if statement
if (action.type === BOOLEAN) action.payload.bool; // Error:
// Property 'bool' does not exist on type '{ bool: boolean; } | { nums: number[]; }'.
// Property 'bool' does not exist on type '{ nums: number[]; }'.
// type narrowing does work with if statement when assigning argument to local variable
// type inference can figure out the correct type.
const actionVar = action;
if (actionVar.type === BOOLEAN) actionVar.payload.bool; // works
}
};Expected behavior:
When checking the discriminant property of a discriminated union the type narrowing should work for switch-case statement as well as if statements.
Actual behavior:
Switch-case statements work for narrowing a discriminated union while if statements do not unless we use type inference by assigning object to variable.
Related Issues:
#11787
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created