Make a single Property in a type Optional in TypeScript

avatar

Borislav Hadzhiev

Sat Mar 19 20222 min read

banner

Photo by John Gibbons

Make a single Property in a type Optional in TypeScript #

To make a single property in a type optional, create a utility type that takes a type and the property name as parameters and constructs a new type with the specific property marked as optional.

index.ts
interface Developer { language: string; age: number; experience: number; } type MakeOptional<Type, Key extends keyof Type> = Omit<Type, Key> & Partial<Pick<Type, Key>>; // 👇️ mark experience as optional type T1 = MakeOptional<Developer, 'experience'>; const dev1: T1 = { age: 30, language: 'ts', }; // 👇️ mark experience and age as optional type T2 = MakeOptional<Developer, 'experience' | 'age'>; const dev2: T2 = { language: 'ts', };

The MakeOptional utility type takes a type and a property name as parameters and returns a new type with the specified property 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 Developer { language: string; age: number; experience: number; } // 👇️ type O1 = { // experience: number; // language: string; // } type O1 = Omit<Developer, 'age'>; // 👇️ type O2 = { // language: string; // } type O2 = Omit<Developer, 'age' | 'experience'>;

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 Developer { language: string; age: number; experience: number; } // 👇️ type P1 = { // language: string; // } type P1 = Pick<Developer, 'language'>; // 👇️ type P2 = { // language: string; // age: number; // } type P2 = Pick<Developer, 'language' | 'age'>;
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 Developer { language: string; age: number; experience: number; } type MakeOptional<Type, Key extends keyof Type> = Omit<Type, Key> & Partial<Pick<Type, Key>>; // 👇️ mark experience as optional type T1 = MakeOptional<Developer, 'experience'>; const dev1: T1 = { age: 30, language: 'ts', }; // 👇️ mark experience and age as optional type T2 = MakeOptional<Developer, 'experience' | 'age'>; const dev2: T2 = { language: 'ts', };

In summary, 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.