Make some of the Properties in a type Optional in TypeScript

avatar

Borislav Hadzhiev

Sat Mar 19 20222 min read

Make some of the Properties in a type Optional in TypeScript #

To make some of the properties in a type optional, create a utility type that takes a type and one or more property names as parameters and constructs a new type with the specified properties marked as optional.

index.ts
interface Employee { id: number; name: string; salary: number; } type MakeOptional<Type, Key extends keyof Type> = Omit<Type, Key> & Partial<Pick<Type, Key>>; // 👇️ make id optional type T1 = MakeOptional<Employee, 'id'>; const emp1: T1 = { name: 'Alice', salary: 100, }; // 👇️ make id and name optional type T2 = MakeOptional<Employee, 'id' | 'name'>; const emp2: T2 = { salary: 200, };

The MakeOptional utility type takes a type and one or more of its property names as parameters and returns a new type with the specified properties marked as optional.

We used the Omit utility type to construct a new type by picking all of the properties from the provided type and removing the specified keys.

index.ts
interface Employee { id: number; name: string; salary: number; } // 👇️ type O1 = { // name: string; // salary: number; // } type O1 = Omit<Employee, 'id'>; // 👇️ type O2 = { // salary: number; // } type O2 = Omit<Employee, 'id' | 'name'>;

Notice that we can specify more than one property name by separating them with a pipe | symbol (called union type).

Now that we have a type with the specified properties removed, we use the Pick utility type to construct a type consisting only of the specified properties and mark them as optional via the Partial utility type.

index.ts
interface Employee { id: number; name: string; salary: number; } // 👇️ type P1 = { // id: number; // } type P1 = Pick<Employee, 'id'>; // 👇️ type P2 = { // id: number; // name: string; // } type P2 = Pick<Employee, 'id' | 'name'>;

The Partial utility type is used to construct a new type with all of the properties of the provided type set to optional.

Here is the entire code snippet.

index.ts
interface Employee { id: number; name: string; salary: number; } type MakeOptional<Type, Key extends keyof Type> = Omit<Type, Key> & Partial<Pick<Type, Key>>; // 👇️ make `id` optional type T1 = MakeOptional<Employee, 'id'>; const emp1: T1 = { name: 'Alice', salary: 100, }; // 👇️ make id and name optional type T2 = MakeOptional<Employee, 'id' | 'name'>; const emp2: T2 = { salary: 200, };

In short, the Omit<Type,Key> part gets us a type that excludes all of the specified properties.

The Pick<Type,Key> syntax gets us a type that consists only of the specified properties.

The Partial<> utility type makes the specified properties optional.

Use the search field on my Home Page to filter through my more than 1,000 articles.