Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

An exception as an alternative to expectNever() #34

Open
rauschma opened this issue Jan 17, 2025 · 0 comments
Open

An exception as an alternative to expectNever() #34

rauschma opened this issue Jan 17, 2025 · 0 comments

Comments

@rauschma
Copy link

class UnsupportedValueError extends Error {
  constructor(value: never, message = `Unsupported value: ${value}`) {
    super(message)
  }
}

// Usage example:
enum Color {Red, Green}
function colorToString(color: Color) {
  switch (color) {
    case Color.Red:
      return 'RED';
    case Color.Green:
      return 'GREEN';
    default:
      throw new UnsupportedValueError(color);
  }
}

I find this code a little more self-explanatory. Compare:

function colorToString(color: Color) {
  switch (color) {
    case Color.Red:
      return 'RED';
    case Color.Green:
      return 'GREEN';
    default:
      return expectNever(color);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant