MediumConcept

What are utility types in TypeScript like Partial, Pick and Omit?

Technology:
TypeScript
Experience:
Junior,
Mid-level

Quick answer

Utility types are built-in helpers that transform an existing type: Partial makes every field optional, Required the opposite, Pick keeps a set of keys, Omit removes them, and Record builds a key/value map.

Detailed explanation

Partial<User> is useful for a PATCH body. Pick<User, "id" | "name"> is a list-row type. Omit<User, "password"> is what you send to the client. Record<Id, User> is a dictionary. ReturnType<typeof fn> and Parameters<typeof fn> pull types from functions so you do not repeat them.

You can write the same things with mapped types; the utilities are the readable version. Interviews sometimes ask you to implement Partial yourself: { [K in keyof T]?: T[K] }.

Example

typescript
type User = { id: string; name: string; password: string };
type PublicUser = Omit<User, "password">;
type UserPatch = Partial<Pick<User, "name" | "password">>;
  • TypeScriptEasy

    What is TypeScript and why do we use it?

    TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It catches type errors in the editor and at build time, and it documents the shape of data for the next person who reads the code.

    Intern 路 Junior 路 Types & Type System
  • TypeScriptMedium

    What are generics in TypeScript?

    Generics are type parameters: they let a function, class or type work with many types while keeping the relationship between inputs and outputs, instead of falling back to any.

    Junior 路 Mid-level 路 Types & Type System
  • TypeScriptMedium

    What is type narrowing in TypeScript?

    Narrowing is when TypeScript shrinks a wide type (such as a union) to a more specific type after a runtime check like typeof, instanceof, in, or a custom type guard.

    Mid-level 路 Senior 路 Types & Type System