Course contentsShow
← TypeScript
Lesson 722 of 1,79617. Mapped TypesFree lesson

Making All Properties Optional

Creating a custom Partial-like type using ? modifier in mapped types.

Making All Properties Optional

What you'll learn: How to recreate TypeScript's built-in Partial<T> utility by using the ? modifier in a mapped type.

The Core Idea

You already know that mapped types let you iterate over an object's keys using keyof. Now you'll learn how to add the ? modifier to make every property optional during that iteration.

Think of it like taking a strict form with all required fields and turning it into a flexible draft where everything becomes optional.

The Syntax

Here's how you build your own Partial-like type:

type MakeOptional<T> = {
  [K in keyof T]?: T[K]
};

The ? after [K in keyof T] tells TypeScript: "this property might be present or absent."

How It Works

type User = {
  id: number;
  name: string;
  email: string;
};

type OptionalUser = MakeOptional<User>;
// Result:
// {
//   id?: number;
//   name?: string;
//   email?: string;
// }

const partialUser: OptionalUser = {
  name: "Alice"
  // id and email can be omitted
};

Practical Use Case

This pattern shines in update functions:

function updateUser(id: number, updates: MakeOptional<User>) {
  // Accept any subset of User properties
}

updateUser(1, { email: "new@example.com" }); // Valid
updateUser(2, { name: "Bob", id: 2 }); // Also valid

Key Takeaway: The ? modifier in mapped types transforms all properties to optional, letting you create flexible versions of strict types—exactly what Partial<T> does under the hood.