Overview
In TypeScript 2.0, the readonly
modifier was added to the language. Properties marked with readonly
can only be assigned to during initialization or from within a constructor of the same class. All other assignments are disallowed.
Let’s take a look at an example. Here’s a simple Point
type that declares two read-only properties, x
and y
:
|
|
We can now create an object representing the point (0|0), the origin, and initialize both x
and y
with the value 0
:
|
|
However, because x
and y
are marked readonly
, we cannot change the value of either property afterwards { 以后 }
|
|
A More Realistic Example
While the above example might seem contrived { 人为的;做作的;不自然的 } (and it is), consider a function like the following:
|
|
The moveX
function should not modify the x
property of the point it was given. Because of the readonly
modifier, the TypeScript compiler will yell at you if you try:
Instead, moveX
should return a new point with updated property values, which could look like this:
|
|
Now the compiler is happy because we’re no longer trying to assign a value to a read-only property. We’re creating a new point whose properties are initialized with updated values, which is perfectly fine.
Read-Only Class Properties
You can also apply the readonly
modifier to properties declared within a class. Here’s a Circle
class with a read-only radius
property and a gettable area
property, which is implicitly read-only because there’s no setter:
|
|
Note that the radius is squared using the ES2016 exponentiation operator. Both the radius
and the area
property can be read from outside the class (because neither one is marked private
), but not written to (because both are marked readonly
):
|
|
Read-Only Index Signatures
Additionally, index signatures can be marked with the readonly
modifier. The ReadonlyArray<T>
type makes use of such an index signature to prevent assignments to indexed properties:
|
|
Because of the read-only index signature, the compiler flags the following assignment as invalid:
|
|
readonly vs. Immutability
The readonly
modifier is part of TypeScript’s type system. It’s only used by the compiler to check for illegal property assignments. Once the TypeScript code has been compiled to JavaScript, all notions of readonly
are gone. Feel free to play around with this little sample to see how read-only properties are transpiled.
Because readonly
is only a compile-time artifact, there’s no protection against property assignments at runtime whatsoever. That said, it’s another feature of the type system that helps you write correct code by having the compiler check for unintended property assignments from within your TypeScript code base.