Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 96 ยท Type Manipulation

Built-in Utility Types

Learn the TypeScript utility types Partial, Required, Readonly, Pick, Omit, Record, Exclude, Extract, ReturnType, Parameters, Awaited and NoInfer with examples.

Real programs rarely need just one version of a type. A User you read from the database has an id; the data you send to create one doesn't. An update form changes only some fields. A settings object should never be modified after startup. Writing a separate interface for each of these by hand means repeating every property, and the copies drift apart the first time someone adds a field.

TypeScript solves this with utility types: generic types that take an existing type and produce a new one. They ship with the compiler (you don't import anything), and they are built from the features you'll learn in the next lessons: mapped types, conditional types and the keyof and indexed access operators. In this lesson you'll use them as ready-made tools. In the following lessons you'll build several of them yourself.

Along the way you'll also meet a small helper for testing types at compile time. It lets an example prove what a type really is, and you'll keep using it for the rest of this chapter.

Testing types with Expect and Equal

When you write console.log(value), you see a value. Types, though, are erased before the program runs (see How TypeScript Works), so you can't print them. In your editor you could hover over a type to see it, but a lesson needs proof that anyone can run. Here are two tiny type aliases that give you exactly that:

TypeScript
type Expect<T extends true> = T;
type Equal<A, B> =
  (<X>() => X extends A ? 1 : 2) extends (<X>() => X extends B ? 1 : 2) ? true : false;
  • Equal<A, B> is a type that evaluates to the literal type true when A and B are the same type, and false otherwise.
  • Expect<T extends true> only accepts true. Passing false breaks its constraint, so the compiler reports error TS2344 and the program doesn't run.

You use them by declaring a throwaway alias: type _check = Expect<Equal<Actual, Expected>>;. If the program compiles and prints its final message, every check passed.

TypeScript Compile-time type checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Now break one on purpose. The next example claims that Point['x'] is string:

TypeScript A failing type check (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler stops with main.ts(10,19): error TS2344: Type 'false' does not satisfy the constraint 'true'. Column 19 points at the Equal<...> argument, so you know exactly which check failed.

Why such a strange definition?

A simpler idea would be "A and B are equal if each is assignable to the other". That test is too forgiving: any is assignable both ways to everything, and a readonly property is assignable both ways to a mutable one, so it would call any equal to string. The trick above compares two generic function types. TypeScript can only decide that <X>() => X extends A ? 1 : 2 matches the version with B if it considers A and B identical, which is a much stricter relation than assignability. You don't have to remember why it works; copy it as a known-good idiom.

Because the check is strict, it sees through some things you might expect to be "the same". An intersection { a: 1 } & { b: 2 } is not identical to the flattened object { a: 1; b: 2 }, even though values of both types look the same. When a check fails for that reason, the mapped types lesson shows a Simplify helper that flattens intersections.

Partial, Required and Readonly

These three change the modifiers on every property of an object type:

Utility What it does
Partial<T> Makes every property optional (?)
Required<T> Removes every ?, so all properties must be present
Readonly<T> Marks every property readonly

Partial is the classic choice for update functions, where the caller passes only the fields that change. Readonly documents that something must not be modified, and the compiler enforces it.

TypeScript Partial updates and Readonly settings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The // @ts-expect-error comment tells the compiler "the next line has a type error, and that's intended". Without the comment, the assignment would fail with error TS2540 (cannot assign to a read-only property). Notice what the last line prints: { theme: 'dark', fontSize: 16 }. readonly exists only at compile time. If you suppress the error, nothing stops the assignment at runtime. For real runtime protection, combine it with Object.freeze(), as the readonly and immutability lesson explains.

All three utilities are shallow: they change only the top-level properties. Readonly<{ tags: string[] }> stops you from replacing tags, but tags.push('x') still compiles. A deep version is a recursive type, which you'll build in Advanced Type-Level Programming.

Pick and Omit

Pick<T, K> keeps only the listed keys; Omit<T, K> keeps every key except the listed ones. Both take keys as a union of string literals.

TypeScript Deriving types with Pick and Omit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

NewUser is a typical "create" shape: the database fills in id and createdAt, so the caller must not send them. When someone later adds a role property to User, all three derived types pick it up automatically.

Pick is strict, Omit is not

Pick requires its keys to exist: Pick<User, 'nmae'> is an error. Omit is defined as Omit<T, K extends keyof any>, which accepts any string, so a typo silently omits nothing:

TypeScript A typo in Pick (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Only the Pick line fails: main.ts(7,26): error TS2344: Type '"nmae"' does not satisfy the constraint 'keyof User'. The Omit line compiles, and Loose is still { id: number; name: string }. If you want a strict version, write one with a constraint: type StrictOmit<T, K extends keyof T> = Omit<T, K>;.

Record

Record<K, V> builds an object type whose keys are K and whose values are all V. With a union of literal keys, it forces you to provide every key, which is perfect for lookup tables. You met it briefly in Index Signatures and Record.

TypeScript Exhaustive lookup tables with Record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

If you add 'archived' to Status, the labels object stops compiling until you add a label for it. Record<string, number> is the open-ended form: any string key, number values. It's equivalent to the index signature { [key: string]: number }.

Exclude, Extract and NonNullable

These three work on union types instead of object types:

  • Exclude<T, U> removes from the union T every member assignable to U.
  • Extract<T, U> keeps only the members assignable to U.
  • NonNullable<T> removes null and undefined.
TypeScript Filtering unions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Extract<Shape, { kind: 'circle' }> is a neat way to pull one member out of a discriminated union. Under the hood, Exclude and Extract are tiny conditional types that run once per union member. The conditional types lesson explains this "distribution" in detail.

Types from functions and classes

Some utilities read information out of function and class types. They're especially useful when a library exports a function but not the types of its arguments or result.

Utility Gives you
ReturnType<F> The return type of function type F
Parameters<F> The parameter types of F, as a tuple
ConstructorParameters<C> The constructor's parameter types, as a tuple
InstanceType<C> The type of the object that new C() creates
Awaited<T> The value a promise resolves to (unwraps nested promises too)

All of them take a type, not a value, so you usually combine them with typeof to get the type of a function or class value:

TypeScript ReturnType, Parameters, InstanceType and Awaited

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A few details worth noticing:

  • Parameters returns a labeled tuple: [customer: string, items: string[], express?: boolean]. The default value made express optional.
  • An async function's return type is Promise<number>, so you need Awaited<ReturnType<...>> to get number. This pairing is very common; the promises lesson uses it a lot.
  • InstanceType<typeof Logger> is just Logger, because a class name used as a type already means "an instance of this class". InstanceType matters when you only have the constructor as a value, for example in a generic factory function.

Writing ReturnType<createOrder> without typeof is a common mistake. createOrder is a value, so TypeScript complains that it "refers to a value, but is being used as a type here" (error TS2749).

NoInfer

NoInfer<T> (added in TypeScript 5.4) is different from the others: it doesn't change a type at all. Instead, it tells the compiler "don't use this position to infer T". This matters when a generic function has several parameters that mention the same type parameter, and you want only one of them to decide what T is:

TypeScript NoInfer picks where inference happens (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The run stops with main.ts(8,55): error TS2345: Argument of type '"huge"' is not assignable to parameter of type '"large" | "medium" | "small"'. (The compiler prints the members of a literal union in its own order, here alphabetical.) That's exactly the bug you want caught. Without NoInfer, TypeScript would infer T from both arguments, widen it to 'huge' | 'large' | 'medium' | 'small', and accept the typo. Delete the last line and the example runs and prints small. The generic constraints lesson shows more uses.

Combining utilities

Utility types compose like functions. A few combinations show up in almost every codebase:

TypeScript
interface Product {
  id: string;
  name: string;
  price: number;
  tags: string[];
}

// Everything except id, all required: the body of a "create" request
type CreateProduct = Omit<Product, 'id'>;

// id required, everything else optional: the body of a "patch" request
type UpdateProduct = Pick<Product, 'id'> & Partial<Omit<Product, 'id'>>;

// A frozen catalog keyed by id
type Catalog = Readonly<Record<string, Readonly<Product>>>;

The next example checks that UpdateProduct behaves as intended: id is required, and the other fields are optional.

TypeScript Create and update shapes from one interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The last call would fail type checking without @ts-expect-error. Suppressing the error shows why the check matters: at runtime patch.id is undefined, so the function throws and the output ends with Runtime error: No product undefined. In real code you'd simply never write that call; the comment is here only to prove that the type catches it.

Keep one source of truth. Define the full entity type once, then derive request bodies, view models and summaries from it with utilities. When the entity changes, the compiler shows you every place that needs attention.

A few more built-ins

You'll meet these less often, but it's good to know they exist:

  • Uppercase<S>, Lowercase<S>, Capitalize<S> and Uncapitalize<S> transform string literal types. They're covered in Template Literal Types.
  • ThisParameterType<F> and OmitThisParameter<F> read or remove an explicit this parameter (see this, parameter destructuring and type predicates).
  • ReadonlyArray<T>, ReadonlyMap<K, V> and ReadonlySet<T> are read-only views of the collection types.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given interface A { x: number; y?: string }, what is Required<A>?

    Required removes the ? modifier from every property, so y becomes a required string.
  2. 2. Does type T = Omit<User, 'nmae'>; compile when User has no nmae property?

    Omit's key parameter is constrained to keyof any (string | number | symbol), not keyof T. Pick is the strict one.
  3. 3. What is Exclude<'a' | 'b' | 'c', 'a' | 'c'>?

    Exclude removes every member assignable to the second type, which leaves only 'b'. Extract would keep 'a' | 'c'.
  4. 4. For async function load() { return 42; }, which type is number?

    An async function returns Promise<number>; Awaited unwraps the promise. ReturnType<load> doesn't compile because load is a value.
  5. 5. Why does Equal<A, B> compare two generic function types instead of checking assignability both ways?

    any is assignable to and from everything, so a two-way assignability test would call any equal to string. The generic function trick requires the types to be identical.

Summary

  • Utility types are built-in generic types that derive new types from existing ones, so you keep one source of truth.
  • Partial, Required and Readonly change the ? and readonly modifiers of every property. They're shallow, and readonly is compile-time only.
  • Pick keeps listed keys and checks that they exist; Omit removes keys but accepts any string, so typos slip through.
  • Record<K, V> builds an object type; with literal keys it forces every key to be present.
  • Exclude, Extract and NonNullable filter union types.
  • ReturnType, Parameters, ConstructorParameters and InstanceType read types out of functions and classes (use typeof on values); Awaited unwraps promises.
  • NoInfer<T> stops a parameter from influencing type inference.
  • type _t = Expect<Equal<A, B>>; proves at compile time that two types are identical; a failure is error TS2344.

Next: Mapped Types