TypeScript Tips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

From Union to Tuple

@RiccardoOdone Suggest a tip

Going from tuple to union is easy but sometimes you need the opposite.

type Screen = "Home" | "Login"
const allScreens: Screen[] = ["Home"] // ⛔️ Missing "Login"
type TuplifyUnion<U extends string, R extends any[] = []> = {
  [S in U]: // for each variant in the union
    Exclude<U, S> extends never // remove it and..
      ? [...R, S] // ..stop recursion if it was the last variant
      : TuplifyUnion<Exclude<U, S>, [...R, S]> // ..recur if not
}[U] // extract all values from the object

type Screen = "Home" | "Login"
type AllScreens = TuplifyUnion<Screen>
const allScreens: AllScreens = ["Home"] // ✅ Does not compile