Alo
Alo

Alo

`Required<Type>` in TypeScript

Photo by Paul Taton on Unsplash

`Required<Type>` in TypeScript

Alo's photo
Alo
ยทApr 2, 2022ยท

2 min read

This article is part of the Series: Typescript utility types, in plain English

Required in a nutshell ๐Ÿฅœ

If Partial<Type> allows you to make properties optional, Required<Type> does the opposite: it makes optional properties mandatory.

type Road = {
    surface:  'Gravel'|'Asphalt'|'Cobblestone'
    widthInMeters?: number,
    speedLimitInKmPerHour?: number
}

type RequiredRoad = Required<Road>

/* This is equivalent to:
type RequiredRoad = {
    surface:  'Gravel'|'Asphalt'|'Cobblestone'|undefined
    widthInMeters: number,
    speedLimitInKmPerHour: number,
}
*/

let cityRoad: RequiredRoad = {
    surface: 'Ashphalt'
}
// ๐Ÿ”ด Error: `widthInMeters` and `speedLimitInKmPerHour` are required!

Example โœ๏ธ

When should you use Required?

Let's imagine we're building a car collector application where we can display the list of cars we own. In this application, we can register cars, update its information, delete them once we sold them and so on.

To do so, we have built a CRUD Rest API.

When we register (i.e. create) a new car, we do not supply the unique identifier. We only supply the information related to our car, such as model, brand and so on. Usually, it's our persistence layer (often a database) that decides on an unique identifier and attach it to our Car object.

type Car = {
    id?: number,
    model: string,
    brand: Brand,
    productionDate: Date,
    /* More information*/
}

function registerNewCar(car:Car){
    /* Register a new car logic: */
    /* Call API, handle errors, etc. */
}

However, in order to update the detail of a car we own, we must give the persistence layer (i.e. DB) a unique identifier so it can find the record.

In that case, we need to provide the id properties.

That's where Required<Type> enters.

    function updateMyCar(car: Required<Car>){
        /* Find the car record using `car.id` and update it. */
        /* `car.id` must be present since we're using Required<Car> */
    }

Conclusion โ˜๏ธ

Required<Type> is another easy to use utility type that allows you to make properties required

ย 
Share this