Skip to content

Switch over discriminated union inside while loop is broken #27493

@WiseBird

Description

@WiseBird

TypeScript Version: 3.2.0-dev.20181002

Search Terms: tagged/discriminated unions unreachable/conditions

Code

enum Types { Str = 1, Num = 2 }
type Instance = StrType | NumType;
interface StrType {
    type: Types.Str;
    value: string;
    length: number;
}
interface NumType {
    type: Types.Num;
    value: number;
}

function func(inst: Instance) {
    if (false) {
        switch (inst.type) {
            case Types.Str: {
                console.log(inst.value.length);
                break;
            }
            case Types.Num: {
                console.log(inst.value.toExponential);
                break;
            }
        }
    }
}

Expected behavior:
No errors

Actual behavior:

Error:(17, 40) TS2339: Property 'length' does not exist on type 'string | number'.
  Property 'length' does not exist on type 'number'.
Error:(21, 40) TS2339: Property 'toExponential' does not exist on type 'string | number'.
  Property 'toExponential' does not exist on type 'string'.

Code

function func2(inst: Instance) {
    while (true) {
        switch (inst.type) {
            case Types.Str: {
                console.log(inst.value.length);
                break;
            }
            case Types.Num: {
                console.log(inst.value.toExponential);
                break;
            }
        }
    }
}

Expected behavior:
No errors

Actual behavior:

Error:(21, 40) TS2339: Property 'toExponential' does not exist on type 'string'.

Playground Link:
Playground

Related Issues:
Not found

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions