Skip to content

TS2454 after assigning a value from an exhaustive switch statement #18362

Closed
@Firehed

Description

@Firehed

TypeScript Version: 2.4.2

Code

enum Level {
  One,
  Two,
}

const doSomethingWithLevel = (level: Level) => {
  let next: Level;
  switch (level) {
    case Level.One:
      next = Level.Two;
      break;
    case Level.Two:
      next = Level.One;
      break;
  }
  return next; // <-- Error here
};

Expected behavior:
Since the switch statement is exhaustive over the enum, the compiler should correctly infer that next is always set and this works without error.

Actual behavior:
(16,10): error TS2454: Variable 'next' is used before being assigned.

Note: replacing the variable assignment with inline returns (e.g. case Level.One: return Level.Two;) appears to negate the problem in this instance, but that isn't an option in the code that this example was derived from since there's additional code that uses the value of next.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixedFixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions