TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Model with different types

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 = { name: string }
type PersistedUser =  User & { id: number }

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

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