TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Laser-focused types

Even if it gets verbose, encoding the rules of the domain in your types will prevent impossible values.

type PostCode = string
const shipTo = (postCode: PostCode) => {}
shipTo("pwned") // ⛔️ Invalid postCode
const shipTo = (postCode: PostCode) => {
  PostCodeModule.format(postCode) // ✅ Encapsulated responsibility
}

// postcode.ts
type Digit = "1" | "2" | "3" | "4" | "6" | "7" | "8" | "9" | "0"
type PostCode = [Digit, Digit, "-", Digit, Digit, Digit]