Johnny.sh

NEVER

Wtf is never type in typescript? Here’s an example:

type Currency = "usd" | "cny" | "cad";

function getLowestDenomination(curr: Currency): [string, number] {
  switch(curr) {
    case "usd":
    case "cad":
      return ["cent", 0.01];
    case "cny":
      return ["mao", 0.1];
    default:
      // this should never happen
      const errMsg: never = curr;
      return errMsg
  }
}

View here on Typescript playground: link

In this example, we create an “enum”-ish thing called currency. By having our default case initialize a variable with type never, we assert that any future additions to the Currency enum will cause a typescript error during compile time, if thi getLowestDenomination function is not updated.

It’s kind of a nice way to enforce extra typesafety in future additions to the codebase

Last modified: October 29, 2022
/about
/uses
/notes
/talks
/projects
/podcasts
/reading-list
/spotify
© 2024