Skip to main content

Command Palette

Search for a command to run...

Literal types with TypeScript

Updated
1 min read
Literal types with TypeScript

I've been recently brushing up on my TypeScript courtesy of codewithmosh.com's Ultimate TypeScript Course. While explicit types are a concept taken from Page 1 of the TypeScript handbook, today I discovered that you can also increase the strictness of a variable even further with literal types:

// This can *only* be "heads" or "tails"
type Coin = "heads" | "tails"; 

const flip = (): Coin => Math.random() < 0.5 ? "heads" : "tails";

console.log(flip());

Obviously, there is a lot of similarity to using an enum , but has the benefit of generating slightly less code after compilation if that's your bag. Personally, I'd probably stick with a backed enum:

enum Coin {
  HEADS = "heads",
  TAILS = "tails",
}

const flip = (): Coin => (Math.random() < 0.5 ? Coin.HEADS : Coin.TAILS);

console.log(flip());

More from this blog

Today I Learned

15 posts