TypeScript in Practice

Everyday types · Lesson 5 of 12 · 13 min

Objects, interfaces and type aliases

type and interface both describe objects. Pick one per codebase and move on; here's the short version of when it matters.

interface User {
  id: string;
  name: string;
  email?: string; // optional
  readonly createdAt: Date; // can't be reassigned
}
 
type Admin = User & { permissions: string[] };

When to use which

Use interfaceUse type
Public object shapesUnions and intersections
Classes implement itMapped and conditional types
You want declaration mergingFunction and tuple types

Utility types you'll use every week

type UserPreview = Pick<User, "id" | "name">;
type NewUser = Omit<User, "id" | "createdAt">;
type UserPatch = Partial<NewUser>;
type UsersById = Record<string, User>;

Partial makes every property optional, including the ones you always need. For update endpoints, prefer Partial<NewUser> & Pick<User, "id">.