TypeScript by Example

Utility Types

Built-in helpers like Partial, Required, Readonly, Record, Pick, Omit, Exclude, and Extract.

TypeScript ships utility types built from mapped types and conditional types. They are available in every TypeScript project.

Partial, Required, Readonly, and Record cover common object transformations.

type User = { id: string; name: string; email: string };
 
type UserPatch = Partial<User>;
type FullUser = Required<UserPatch>;
type ImmutableUser = Readonly<User>;
 
type RolePermissions = Record<"admin" | "viewer", string[]>;

Pick and Omit reshape objects. Exclude and Extract reshape unions.

type Article = {
  id: string;
  title: string;
  body: string;
  authorId: string;
};
 
type ArticleSummary = Pick<Article, "id" | "title">;
type PublicArticle = Omit<Article, "authorId">;
 
type Status = "pending" | "active" | "deleted";
type LiveStatus = Exclude<Status, "deleted">;
type TerminalStatus = Extract<Status, "deleted">;

In production

Use Partial<T> at update boundaries, not deep inside functions where data should already be complete. Utility types are contracts, so keep them close to the layer where that contract changes.

Enjoyed this? Get more software craft delivered to your inbox.