TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Polymorphic types

You can pass a context as a type parameter to specify properties' types.

type User<Id, CreatedAt> = {
  id: Id,
  email: string,
  createdAt: CreatedAt,
}

type PersistedUser = User<number, Date>
// ⛔️ Caller specifies types

type NewUser = User<null, null>
// ⛔️ Multiple nulls
type Context = "Persisted" | "New"

type User<Ctx extends Context> = {
  id: Ctx extends "Persisted" ? number : null,
  email: string,
  createdAt: Ctx extends "Persisted" ? Date : null,
}

type PersistedUser = User<"Persisted"> // ✅
type NewUser = User<"New"> // ✅