TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Check Authorization With Types (again)

Moving authorization from value to type level can make your code simpler and bullet-proof.

const dropDatabase = (performedBy: User) => {
  if (performedBy._kind !== 'user') { return } // ⛔️ Should be ===
  // ...
}

dropDatabase(member) // ⛔️
type MemberKind = "user"
type User = { _kind: "admin" } | { _kind: "editor" } | { _kind: MemberKind }
type FilterPrivileged<U extends User> = U extends { _kind: MemberKind } ? never : U
type Privileged = FilterPrivileged<User>

const dropDatabase = (performedBy: Privileged) => {
  // ...
}

dropDatabase(member) // ✅ Does not compile