DEV Community

Leonardo Oliveira
Leonardo Oliveira

Posted on • Updated on

002 - TSExpert | Readonly Typescript

Wasup, guys...

I hope you guys are doing well

Today, one more time we're crafiting other typescript utility for studies purposes. The guy of the moment is the Readonly utility.

That built-in utility get a type N and transform all of their properties in readonly properties, creating a safe type without overrides.

Out of the box, typescript already have this utility for production uses. But we'll creating a clone of it today.

Let's see how it works in your default implementation:

Image description

Alright, let's assume that on this case for some reason, assigning this prop was not allowed, because the admin role is a security level, and cannot be changed manually.

In this case, typescript not helping us, now is the time of Readonly utility shine bright.

We can use it, for set all of these properties as readonly property, that is, we're safing lock all properties to never alter.

It looks something like this:

Image description

In our Props type declaration, we wrapped it in Readonly default built-in utility and from now on, all props are locked, their are readonly properties.

Instantly we got an error:

Image description

And typescript now, dont allow us to override an readonly prop, this is very useful in this and others cases.

🔨 As usual, now we'll create our own implementation of this utility 🔧


"What a cannot create, i don't understand" - Feynman R.

Our own implementation

This utility is very easy to create, the only thing we need to do is create a new object with a readonly prefix in each property.

Let's call it, MyReadonly, our utility will receive a generic , and override each prop type with readonly, in this way:

Image description

Now, works as the built-in utility.

Image description

🤩 That's it for today, folks! 🤩

Follow me for more content about Typescript, Javascript, React and stuffs of these stack content.

Top comments (0)