How to use Conditional and Mapped Types In Typescript

This approach introduces a utility type called OptionalProperty that makes a specified property optional. Unlike previous methods, it employs advanced TypeScript features for a streamlined solution.

Syntax:

type OptionalProperty<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

Parameters:

  • T: The original type.
  • K: The key of the property you want to make optional.

This utility type first removes the specified property from the type (Omit<T, K>) and then reintroduces it as optional using Partial<Pick<T, K>>.

Example: Here, we define a utility type OptionalProperty that takes a generic type T and a property key K. It utilizes TypeScript’s Omit and Partial to make the specified property optional. The resulting PersonWithOptionalLastName type is then used to create an object with the lastName property being optional.


JavaScript
type OptionalProperty<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

interface Person {
    firstName: string;
    lastName: string;
    age: number;
}

// Make 'lastName' property optional
type PersonWithOptionalLastName = OptionalProperty<Person, 'lastName'>;

// Example usage:
const person1: PersonWithOptionalLastName = { firstName: 'John', age: 25 };
const person2: PersonWithOptionalLastName = { firstName: 'Alice', lastName: 'Johnson', age: 30 };

console.log(person1); // Output: { firstName: 'John', age: 25 }
console.log(person2); // Output: { firstName: 'Alice', lastName: 'Johnson', age: 30 }

Output:

{ firstName: 'John', age: 25 }
{ firstName: 'Alice', lastName: 'Johnson', age: 30 }


How to Make a Single Property Optional in TypeScript ?

TypeScript is a popular programming language that is a strict syntactical superset of JavaScript, adding optional static typing and class-based object-oriented programming to the language. One useful feature of TypeScript is the ability to specify optional properties in interfaces and classes, allowing you to define an object type that may or may not have certain properties.

Similar Reads

Using Utility Type

This approach employs a utility type named MakeOptional. The utility type uses TypeScript’s Omit to exclude the specified property and introduce the ? syntax to mark it as optional....

Using Conditional and Mapped Types

This approach introduces a utility type called OptionalProperty that makes a specified property optional. Unlike previous methods, it employs advanced TypeScript features for a streamlined solution....