TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Model with different types (2)

By using different types you can make the compiler check you are passing the right things to the right functions.

type User = { id?: number, name: string }

const createUser = (user: User) => {}
const updateUser = (user: User) => {}

createUser(persistedUser) // ⛔️
updateUser(newUser) // ⛔️
type User<Id> = {
  id: Id,
  email: string,
}
type NewUser = User<null>
type PersistedUser = User<number>

const createUser = (user: NewUser) => {}
const updateUser = (user: PersistedUser) => {}

createUser(persistedUser) // ✅ Does not compile
updateUser(newUser) // ✅ Does not compile