JavaScript and TypeScript course ยท Module 6: TypeScript Basics

TypeScript Utility Types

7 min read ยท
In this lesson10

Dr. Henry Wu reviews the genetic database of Jurassic Park. "We have a Dinosaur interface with 15 properties," he says, "but for the update form I need only 5, and for the preview just 3. Do I have to create a separate interface for each case?" Copying interfaces has a hidden cost: when Dinosaur gets a new field, every copy has to be fixed by hand, and someone always forgets one. Fortunately, TypeScript offers Utility Types, ready-made transformations that create new types based on existing ones.

What are utility types?

Utility types are generic types built into TypeScript that transform existing types into new ones. You pass the type to transform in angle brackets, like the argument of the generic functions from earlier lessons. You do not need to import them, and they disappear after compilation, because they exist only while types are being checked. Instead of separate interfaces, you have one base type from which you derive variants, like breeding lines grown from a single DNA sample.

Partial<T> - all properties optional

In the examples we will use a simplified interface with five fields. The dietType field accepts one of three values written as a union of literals. Partial<T> makes all properties of type T optional. It is the ideal type for an update, where we do not want to require every field:

interface Dinosaur {
  name: string;
  species: string;
  dangerLevel: number;
  enclosureId: string;
  dietType: 'herbivore' | 'carnivore' | 'omnivore';
}

// Partial<Dinosaur> = all fields optional
type DinosaurUpdate = Partial<Dinosaur>;

// Now we can pass only the changed fields
function updateDinosaur(id: string, changes: DinosaurUpdate): void {
  console.log(`Updating dinosaur ${id}:`, changes);
}

// Correct - we pass only what we are changing
updateDinosaur('DINO-001', { dangerLevel: 9 });
updateDinosaur('DINO-002', { name: 'Blue', enclosureId: 'E-7' });

The Dinosaur interface itself did not change, because Partial creates a new type next to it. Checking still works: a typo such as dangerLvl gets reported. Partial is shallow, so the fields of a nested object remain required.

Required<T> - all properties required

Required<T> works the opposite way to Partial: it removes the question mark, so all properties, even optional ones, become required:

interface DinosaurConfig {
  name: string;
  trackingChip?: boolean;  // optional
  feedingSchedule?: string; // optional
}

// Required<DinosaurConfig> = everything required
type CompleteDinosaurConfig = Required<DinosaurConfig>;

// Now trackingChip and feedingSchedule are also required
const config: CompleteDinosaurConfig = {
  name: 'Rex',
  trackingChip: true,        // must be provided
  feedingSchedule: '08:00'   // must be provided
};

If feedingSchedule were missing, the compiler would report the missing property. This is useful when a configuration must be complete after the default values have been filled in.

Pick<T, K> - select properties

Pick<T, K> creates a new type containing only the selected properties of T. The second parameter is a list of field names joined with |:

// Only name and species from the full Dinosaur interface
type DinosaurPreview = Pick<Dinosaur, 'name' | 'species'>;

// DinosaurPreview = { name: string; species: string; }

const preview: DinosaurPreview = {
  name: 'Blue',
  species: 'Velociraptor'
};

// Useful e.g. for a list displayed on screen
function renderDinosaurList(dinosaurs: DinosaurPreview[]): void {
  dinosaurs.forEach(dino => {
    console.log(`${dino.name} (${dino.species})`);
  });
}

Pick checks that the given keys exist: Pick<Dinosaur, 'enclosureID'> with a typo ends in a compile error right away. The field types carry over unchanged, so name is still a string.

Omit<T, K> - omit properties

Omit<T, K> works the opposite way to Pick and creates a new type without the selected properties:

// Dinosaur without enclosureId (e.g. for a newly discovered species)
type DinosaurWithoutEnclosure = Omit<Dinosaur, 'enclosureId'>;

const newDiscovery: DinosaurWithoutEnclosure = {
  name: 'New species',
  species: 'Unknownus rex',
  dangerLevel: 5,
  dietType: 'carnivore'
  // we do not need to provide enclosureId
};

// Omit multiple fields at once
type DinosaurBasicInfo = Omit<Dinosaur, 'enclosureId' | 'dangerLevel'>;

Omit does not remove anything from existing objects; it only describes a new shape. It also has a trap: unlike Pick, it does not check whether a key exists, so Omit<Dinosaur, 'enclosureID'> passes without an error and omits nothing. That is why, when you keep only a few fields, I recommend Pick.

Record<K, V> - typed dictionary

Record<K, V> creates an object type whose keys have type K and whose values have type V:

// Dictionary: zone name -> list of dinosaurs
type ZoneMap = Record<string, Dinosaur[]>;

const parkZones: ZoneMap = {
  'Zone-A': [{ name: 'Rex', species: 'T-Rex', dangerLevel: 10, enclosureId: 'E-1', dietType: 'carnivore' }],
  'Zone-B': [{ name: 'Trike', species: 'Triceratops', dangerLevel: 3, enclosureId: 'E-2', dietType: 'herbivore' }]
};

// Record with limited keys (union type)
type DietCount = Record<'herbivore' | 'carnivore' | 'omnivore', number>;

const census: DietCount = {
  herbivore: 45,
  carnivore: 12,
  omnivore: 8
};

With a string key, the dictionary accepts any zone name. With a union of keys, every one of them is mandatory, so if omnivore were missing from the census, the compiler would report an error. It is a great way to make sure no category is forgotten.

Readonly<T> - immutable type

Readonly<T> makes all properties read-only:

type FrozenDinosaur = Readonly<Dinosaur>;

const frozenDNA: FrozenDinosaur = {
  name: 'Amber Specimen',
  species: 'Unknown',
  dangerLevel: 0,
  enclosureId: 'LAB-1',
  dietType: 'herbivore'
};

// frozenDNA.name = 'Changed'; // Error! Cannot assign to 'name' because it is a read-only property

Unlike Object.freeze() from the lesson on prototypes, this protection works only at compile time. In running JavaScript the object remains an ordinary object. Readonly is also shallow and does not protect nested objects.

Combining utility types

The real power comes from combining several utility types. Read such types from the inside out:

// Dinosaur creation form: all fields required EXCEPT enclosureId
type CreateDinosaurForm = Omit<Dinosaur, 'enclosureId'> & {
  enclosureId?: string; // optional when creating
};

// Edit form: only selected fields, all optional
type EditDinosaurForm = Partial<Pick<Dinosaur, 'name' | 'dangerLevel' | 'enclosureId'>>;

// Immutable preview with selected fields
type DinosaurReadonlyPreview = Readonly<Pick<Dinosaur, 'name' | 'species' | 'dangerLevel'>>;

const readonlyPreview: DinosaurReadonlyPreview = {
  name: 'Blue',
  species: 'Velociraptor',
  dangerLevel: 8
};
// readonlyPreview.dangerLevel = 10; // Error!

EditDinosaurForm first selects three fields and then makes them optional. In CreateDinosaurForm the & sign is an intersection: it combines the type without enclosureId with an object in which that field is optional.

Summary

TypeScript Utility Types allow creating variants of existing types without code duplication:

TypeAction
Partial<T>All fields optional
Required<T>All fields required
Pick<T, K>Select specific fields
Omit<T, K>Omit specific fields
Record<K, V>Typed dictionary
Readonly<T>All fields read-only

That is not the whole toolbox: the TypeScript documentation also describes ReturnType, Parameters, Exclude and NonNullable, among others. As Dr. Wu says: "Don't create 10 separate interfaces when one base type and utility types will handle it elegantly and safely!" In the next lesson we will look at TypeScript configuration and the tools around the compiler.

Practice

The sandbox contains the Dinosaur interface with Partial and Pick examples. Add a variant with Omit and deliberately make a typo in a key to see the difference between Pick and Omit.

Code for this lesson: index.ts
// TypeScript Utility Types
// Dinosaur management system in Jurassic Park

// Base dinosaur interface
interface Dinosaur {
  name: string;
  species: string;
  dangerLevel: number;
  enclosureId: string;
  dietType: "herbivore" | "carnivore" | "omnivore";
}

// === Partial<T> - all fields optional ===
type DinosaurUpdate = Partial<Dinosaur>;

function updateDinosaur(id: string, changes: DinosaurUpdate): void {
  console.log("Updating dinosaur " + id + ":", changes);
}

updateDinosaur("DINO-001", { dangerLevel: 9 });
updateDinosaur("DINO-002", { name: "Blue", enclosureId: "E-7" });

// === Pick<T, K> - pick properties ===
type DinosaurPreview = Pick<Dinosaur, "name" | "species">;

const preview: DinosaurPreview = {
  name: "Blue",
  species: "Velociraptor",
};
console.log("\nPreview:", preview);

// === Omit<T, K> - omit properties ===
type DinosaurWithoutEnclosure = Omit<Dinosaur, "enclosureId">;

const newDiscovery: DinosaurWithoutEnclosure = {
  name: "New species",
  species: "Unknownus rex",
  dangerLevel: 5,
  dietType: "carnivore",
};
console.log("\nNew discovery:", newDiscovery);

// === Record<K, V> - a typed dictionary ===
type DietCount = Record<"herbivore" | "carnivore" | "omnivore", number>;

const census: DietCount = {
  herbivore: 45,
  carnivore: 12,
  omnivore: 8,
};
console.log("\nCensus:", census);

// === Readonly<T> - an immutable type ===
type FrozenDinosaur = Readonly<Dinosaur>;

const frozen: FrozenDinosaur = {
  name: "Amber Specimen",
  species: "Unknown",
  dangerLevel: 0,
  enclosureId: "LAB-1",
  dietType: "herbivore",
};
console.log("\nFrozen:", frozen);
// frozen.name = "Changed"; // Error! Read-only

// === Combining utility types ===
type EditForm = Partial<Pick<Dinosaur, "name" | "dangerLevel" | "enclosureId">>;

const edit: EditForm = { dangerLevel: 7 };
console.log("\nEdit form:", edit);

Remember: the base type is the original DNA sample, and utility types breed variants from it, so a fix in the sample reaches every line at once.

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which utility type in TypeScript makes ALL object properties optional?

  2. 2. What does the Omit<T, K> type do in TypeScript?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Use Pick, Omit, and Partial on the Dinosaur interface to create type variants.

  • Horizontal ordering

    Arrange the elements of the Pick utility type usage:

  • Vertical ordering

    Order TypeScript concepts from simplest to most complex:

  1. QuestionUtility Type Partial
  2. QuestionThe Omit Type
  3. Coding taskPractice: Utility Types
  4. Put in orderPick Syntax
  5. QuestionThe Pick Type
  6. Put in orderTypeScript Type Complexity

Useful articles