Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript compiler not complaining about missing switch case [duplicate]

Consider the following code:

  enum MyEnum {
    Enum1,
    Enum2
  }

  function switchOverEnum(myEnum: MyEnum) {
    switch (myEnum) {
      case MyEnum.Enum1:
        console.log('it is an enum1');
        break;
      // I am missing the case MyEnum.Enum2 here,
      // but the TypeScript compiler does not complain
    }
  }

I am using this in a project created using create-react-app. My expectation is that TypeScript complains that the case MyEnum.Enum2 is not handled, but it doesn't. How can I confiugre the TypeScript compiler to do so?

like image 872
stefan.at.wpf Avatar asked Mar 11 '26 10:03

stefan.at.wpf


1 Answers

Do it this way


enum MyEnum {
  Enum1,
  Enum2
}

function switchOverEnum(myEnum: MyEnum) {
  switch (myEnum) {
    case MyEnum.Enum1:
      console.log('it is an enum1');
      break;
   
    case MyEnum.Enum2:
      console.log('it is an enum2');
      break;
   
    default:
      const exhaustiveCheck: never = myEnum;
      throw new Error(`Unhandled Enum case: ${exhaustiveCheck}`);
  }

}

Or with the anonymous function

  default:
      ((x: never) => {
        throw new Error(`${x} was unhandled!`);
      })(c);

see here playground

For more ways see here

like image 137
Yoel Avatar answered Mar 13 '26 02:03

Yoel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!