Skip to content

Conversation

@merlinnot
Copy link
Contributor

Description

This is only a type safety change, does not change actual behaviour. Whereas the comment before the default stated that it should never get there unless TypeScript does its job, it didn't hold true - an error was thrown in the default case, which is a branch of execution that is perfectly correct. An unreachable code is represented by a never type in TypeScript.

This PR adds a function that accepts a parameter of type never, which will not be allowed by the compiler. If the impossible happens, a readable error will be thrown.

Code sample

// This will compile
function f(x: 'a' | 'b'): void {
  switch (x) {
    case 'a':
    case 'b':
      console.log('reachable');

      return;
    default:
      assertNever(x);
  }
}

// While this will throw an error during compilation
function f(x: 'a' | 'b'): void {
  switch (x) {
    case 'a':
      console.log('reachable');

      return;
    default:
      assertNever(x);
  }
}

Copy link
Contributor

@thechenky thechenky left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this looks great!

@thechenky thechenky merged commit 36916b8 into firebase:master Jul 15, 2019
@merlinnot merlinnot deleted the exhaustive-switch branch July 16, 2019 15:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants