Make all properties optional in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 19, 2022

banner

Photo from Unsplash

Make all properties optional in TypeScript #

Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {};. The Partial utility type constructs a new type with all properties of the provided type set to optional.

index.ts
interface Employee { id: number; name: string; salary: number; } const emp: Partial<Employee> = {}; emp.name = 'James';

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

index.ts
interface Employee { id: number; name: string; salary: number; } // 👇️ type T = { // id?: number | undefined; // name?: string | undefined; // salary?: number | undefined; // } type T = Partial<Employee>;

The same approach can be used to get a type that consists of an object's properties where all of them are marked as optional.

index.ts
const obj = { id: 1, name: 'James', salary: 100, }; // 👇️ type T = { // id?: number | undefined; // name?: string | undefined; // salary?: number | undefined; // } type T = Partial<typeof obj>;

Notice that we had to use the typeof type operator, because Partial expects a type.

You can see how the built-in Partial type is implemented in TypeScript's Github repository.

index.ts
/** * Make all properties in T optional */ type Partial<T> = { [P in keyof T]?: T[P]; };

The ?: syntax is called a mapping modifier and is used to affect optionality.

You can also see +?: being used, which achieves the same result. If you don't add a prefix, then + is assumed.

The utility type basically takes all of the properties of the provided type and marks them as optional.

Mapping modifiers can affect optionality both ways, e.g. you can also use them to make all of the properties of an interface required by prefixing the ?: with a minus (-?:).

If you don't add a prefix, then + is assumed, like in the Partial utility type.
index.ts
/** * Make all properties in T required */ type Required<T> = { [P in keyof T]-?: T[P]; };

This is the code for the Required utility type, which makes all of the properties of the provided type required.

Notice that the only character that changed is the minus in front of the question mark to use a mapping modifier that removes optionality.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.