Alo
Alo

Alo

`Readonly<Type>` in TypeScript

Photo by Tim Arnold on Unsplash

`Readonly<Type>` in TypeScript

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

2 min read

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

Readonly in a nutshell ๐Ÿฅœ

Another easy-to-use utility type that comes in handy when you want to freeze the properties of your object.

type Road = {
    speedLimitInKmPerHour: number
}

type  SafeRoad = Readyonly<Road>

/* This is equivalent to:
type RequiredRoad = {
    readonly speedLimitInKmPerHour: number,
}
*/

let cityRoad: SafeRoad = {
    speedLimitInKmPerHour: 50
}

// Trying to overwrite the speed limit so we can drive faster ๐Ÿ‘Ž
cityRoad.speedLimitInKmPerHour = 90;

// ๐Ÿ”ด Error: Cannot assign to 'speedLimitInKmPerHour' because it is a read-only property.

Example โœ๏ธ

When should you use Readonly?

The example above show you when you would want to use Readonly<Type>: anytime you want properties or object to be immutable.

In the case above, we want to make sure that no one can override the speed limit. It would be unsafe.

Note that we could also choose which properties are to be immutable, by prefixing the property name with readonly.

Another great example would be making the id of a readonly property, since we do not want the id to be mutable.

type Train = { readonly id: number, /* other properties as required */ } // We can be sure that no one overwrites the trainid๐Ÿ‘

Finally, you might find another use case for it. If you deal with frozen object (i.e.Object.freeze()) you might want to make the type a Readonly one; but this is very rare.

Conclusion โ˜๏ธ

I might start to sound like a broken record: Readonly<Type> is yet again an easy utility type to use.

Now you may start to wonder: well, that's great, but is there a way we can combine Readonly<T>, Required<T> and Partial<T>? Of course! That's the power of utility type.

Next article we will explore Omit and Pick which allow you to combine utility types.

ย 
Share this