Skip to content

Switch narrowing regression with nested unions #29012

Closed
@jwmerrill

Description

@jwmerrill

TypeScript Version: 3.2.2, 3.3.0-dev.201xxxxx

Search Terms: 3.2 switch union narrowing regression

Code

type Additive = '+' | '-';
type Multiplicative = '*' | '/';

interface AdditiveObj {
    key: Additive
}

interface MultiplicativeObj {
    key: Multiplicative
}

type Obj = AdditiveObj | MultiplicativeObj

export function foo(obj: Obj) {
    switch (obj.key) {
        case '+': {
            onlyPlus(obj.key);
            return;
        }
    }
}

function onlyPlus(arg: '+') {
  return arg;
}

Expected behavior:
obj.key is narrowed to '+' in the switch and the call to onlyPlus(obj.key) type checks successfully.

Actual behavior:
obj.key is narrowed to Additive in the switch and the call to onlyPlus(obj.key) fails to type check

Playground Link: http://www.typescriptlang.org/play/#src=type%20Additive%20%3D%20'%2B'%20%7C%20'-'%3B%0D%0Atype%20Multiplicative%20%3D%20'*'%20%7C%20'%2F'%3B%0D%0A%0D%0Ainterface%20AdditiveObj%20%7B%0D%0A%20%20%20%20key%3A%20Additive%0D%0A%7D%0D%0A%0D%0Ainterface%20MultiplicativeObj%20%7B%0D%0A%20%20%20%20key%3A%20Multiplicative%0D%0A%7D%0D%0A%0D%0Atype%20Obj%20%3D%20AdditiveObj%20%7C%20MultiplicativeObj%0D%0A%0D%0Aexport%20function%20foo(obj%3A%20Obj)%20%7B%0D%0A%20%20%20%20switch%20(obj.key)%20%7B%0D%0A%20%20%20%20%20%20%20%20case%20'%2B'%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20onlyPlus(obj.key)%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20return%3B%0D%0A%20%20%20%20%20%20%20%20%7D%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Afunction%20onlyPlus(arg%3A%20'%2B')%20%7B%0D%0A%20%20return%20arg%3B%0D%0A%7D%0D%0A

Related Issues:

Note:
This seems to be a regression between TS 3.1 and TS 3.2

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptDomain: Control FlowThe issue relates to control flow analysisFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions