Make all properties required in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 19, 2022

banner

Photo from Unsplash

Make all properties required in TypeScript #

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

index.ts
interface Employee { id?: number; name?: string; salary?: number; } const emp: Required<Employee> = { id: 1, name: 'Tom', salary: 1000, };

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

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

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

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

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

When prefixed with a minus, the mapping modifier removes the optionality of the type's properties.

The utility type basically takes all of the properties of the provided type and removes their optionality (makes them required).

Mapping modifiers can affect optionality both ways, e.g. you can also use them to make all of the properties of a type optional by prefixing the ?: with a plus (+?:).

If you don't add a prefix, then + is assumed.

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

This is the code for the Partial utility type, which makes all of the properties in a type optional.

Notice that the only difference between between the two types is the minus in front of the question mark in the Required type.

The -?: syntax removes optionality whereas, ?: (or +?:) makes all properties in the type optional.

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.