DEV Community

Leonardo Oliveira
Leonardo Oliveira

Posted on • Edited on

1

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 🔧

Why?...

"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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay