DEV Community

Discussion on: If-Else or Switch-Case: Which One to Pick?

Collapse
 
pinotattari profile image
Riccardo Bernardini

A side note from a different language...

In Ada you can use switch .. case (actually it is case .. when like in Ruby) only with discrete types: integers and enumerations. The nice part of the case in Ada is that you are obligated to specify all the cases. It can seem like a burden, but it saved me from many bugs that would had happened because I forgot to update a case after adding a new item to an enumeration type.

Of course there is the "default" case (when other), but I try to avoid it since it "disables" the safety check that all the cases are specified.

What about when you do a case with an integer? You cannot, of course, specify all the integers... Well, in that case you can use the when other (it is legit, after all), but often is better to define a new integer type with explicit bounds.

Collapse
 
peerreynders profile image
peerreynders

TypeScript supports exhaustiveness checking on union types.

type Grade = 'A+' | 'A' | 'B+' | 'B' | 'C' | 'D' | 'F';

function studentFinalResult(grade: Grade): string {
  switch (grade) {
    case 'A+':
      return 'Nailed It! 🥳';
    case 'A':
    case 'B+':
    case 'B':
      return 'Passed 💃';
    case 'C':
      return 'Barely Survived 😌';
    case 'D':
    case 'F':
      return 'Failed 😢';
    default:
      const _exhaustiveCheck: never = grade; // "Type 'string' is not assignable to type 'never'".
      return _exhaustiveCheck;               // if one of the union type values is missing
  }
}

console.log(studentFinalResult('A+')); // "Nailed It! 🥳"
Enter fullscreen mode Exit fullscreen mode

playground