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

Adding and Removing optional with + and -

Use +? and -? to explicitly add or remove optional modifiers in mapped types.

Adding and Removing optional with +? and -?

You'll learn: How to explicitly add or remove the ? optional modifier on properties when creating mapped types.


The Core Idea

Just like you can add or remove readonly with +readonly and -readonly, you can control optionality in mapped types using +? and -?.

  • +? makes properties optional (adds the ? modifier)
  • -? makes properties required (removes the ? modifier)

This is incredibly useful when transforming existing types — you might need to make all properties optional for partial updates, or ensure all properties are required for validation.


Syntax and Usage

// Make all properties optional
type MakeOptional<T> = {
  [K in keyof T]+?: T[K];
};

// Make all properties required
type MakeRequired<T> = {
  [K in keyof T]-?: T[K];
};

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

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

type RequiredUser = MakeRequired<User>;
// { id: string; name: string; email: string; }

The + is actually the default — writing ? is the same as +? — but being explicit can improve readability.


When This Matters

You'll use -? when you need to ensure a type has no optional properties (like when validating data before database insertion), and +? when creating types for partial updates or patches.

Key Takeaway: Use +? to add optionality and -? to remove it in mapped types, giving you fine control over whether properties are required or optional.