8000 Exhaustive switch on a type union with a default case yields TS2339: Property 'x' does not exist on type 'never' · Issue #9838 · microsoft/TypeScript · GitHub
[go: up one dir, main page]

Skip to content
Exhaustive switch on a type union with a default case yields TS2339: Property 'x' does not exist on type 'never' #9838
Closed
@ghost

Description

TypeScript Version: 2.0.0

Code

type TestType = 'foo' | 'bar';

interface TestInterface {
  type : TestType;
}

class Test {
  test = (param : TestInterface) : boolean => {
    switch (param.type) {
      case 'foo' : return true;
      case 'bar' : return false;
      default    : throw Error("Invalid type: "+ param.type); // TS2339: Property 'type' does not exist on type 'never'.
    }
  }
}

Expected behavior:
The code compiles with no errors.

Actual behavior:
tsc test.ts
test.ts(14,53): error TS2339: Property 'type' does not exist on type 'never'.

I understand the compiler knows that with the current code the default case can never be reached and the type property can not have any possible valid TestType value in this case but the whole point of having a default case is to limit the scope of the human error, compiling with a different TS version, compiler flags etc. It can also be considered a safe coding practice.

The workaround is easy but ugly and should not be necessary:

default    : throw Error("Invalid type: "+ (<any>param).type);

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

    0