Mutability 12 exercises

Use the Readonly Type Helper to Create Read-Only Objects in TypeScript

TypeScript's Readonly type helper ensures that all object properties are read-only:


If you try to modify a read-only property, you will encounter errors. However, this doesn't alter the characteristics of the properties themselves - they continue to re

Loading solution


00:00 Ready? Sometimes the answer is just right there. Read-only. And read-only, it applies to objects, and it basically says, OK, for all the objects in here, this is now going to be read-only. And so you're going to get errors on every single one of these because it's a read-only property. Still doesn't change anything about the properties. They're still totally optional.

00:19 Still got all of the members of the literals all tied in. But it just turns them read-only. This only happens one level deep. Like most of the TypeScript type helpers, it only operates on the first level. So it won't make it kind of like, how do you say, recursively read-only or anything like that.

00:37 But it just operates like an object.freeze, freezing the object, making sure that on the type level, you can't change anything about it. And again, nothing happens at runtime, just extra type information. Really nice.