Typescript provides a way to indicate props in an object / type, or an entire type, as read only.
Props in an object
Consider this example -
|
|
In the code block we have specified the prop name
as read-only.
We can very much change the color of an object derived from Fruit
.
|
|
But, we cannot change the name -
|
|
In normal Javascript, you would have defined the property as non-writable using property descriptors to achieve the same effect.
Props in a type
We create types similar to an object, and we can make one or more of the props read-only.
|
|
Note that setting name
during initialization is allowed, but the prop cannot be changed later.
All props in a type
We can make entire types as read-only by processing it through a Readonly
type.
|
|
We get an error if we try to change any prop -
|
|
In normal Javascript, you can achieve the same effect using Object.freeze()
.