Francesco Meli
Francesco Meli

Reputation: 2700

Not all code paths return a value: if vs switch

Why, for the following snippet, the compiler screams at me saying

Not all code paths return a value

const someFunction = (e: "A" | "B") => {
    if (e == "A") return "letter-A";
    if (e == "B") return "letter-B";
}

but when using the switch statement it goes back to sleep?

const someFunction = (e: "A" | "B") => {
    switch (e) {
      case "A": return "letter-A"
      case "B": return "letter-B"
    }
}

Upvotes: 0

Views: 142

Answers (1)

jcalz
jcalz

Reputation: 329523

Because there's no mechanism in place to detect a series of if statements as being possibly exhaustive the same way there is for a switch statement. There is an open suggestion at microsoft/TypeScript#21985 to implement such a feature. If you want to see it happen, you might want to go there and give it a 👍.

For now the only way to fix this (without refactoring to switch) is to either add a dummy return or throw statement. If you find yourself doing this often you can write a helper function which only accepts inputs that have been narrowed to never due to impossibility, which always throws, and return the result of that:

const assertNever = (x: never): never => 
  { throw new Error("Oops, unexpected value " + String(x)) };

const someFunction = (e: "A" | "B"): string => {
  if (e == "A") return "letter-A";
  if (e == "B") return "letter-B";
  return assertNever(e);
}

Playground link to code

Upvotes: 3

Related Questions