Specifying Read-only Object Properties
The solution to this challenge is pretty straightforward.
TypeScript offers a first-class approach for this by adding the readonly
keyword before the property, like so:
type User = { readonly id: number; name: string; age: number;};
With this change, the id
property
Transcript
00:00 Okay, the solution here is pretty simple. TypeScript gives us a first class way to do that. We can just add read-only before the ID property, just there. And now the ID property is read-only and the rest of them are still mutable. So by default, object properties are mutable in TypeScript. And this is because by default,
00:19 object properties are mutable in JavaScript too. Adding read-only here doesn't do anything at runtime, right? It's just literally a type annotation, but it just gives you a bit more information and says, okay, if you try to mutate this, you can't do it because it's a read-only property. And I think a lot more people should be using read-only in their type definitions,
00:38 because how often really are you mutating objects directly? Usually in the kind of front-end or very immutable world that we live in, immutability is a key concept in front-end applications and back-end applications. Really, you want a lot of your properties to be read-only. So I think you should probably be using this a fair amount.
00:57 But anyway, it's a very, very useful little type annotation that can really save you from quite a lot of bugs.