How the TypeScript Readonly Type Works
Let's take a look at how the Read-only type works in TypeScript.
Join the DZone community and get the full member experience.
Join For FreeTypeScript has a number of utility types, which are types specifically created by TypeScript to solve a problem. In this article, let's look at the Readonly
type.
TypeScript Readonly Type
As the name suggests, the Readonly
type in TypeScript suggests that a particular type is read-only.
Let's look at an example. Below, we don't want anyone to update any part of myObject
. We can make it a read-only object like so:
type User = {
firstName: string,
lastName: string
}
let firstUser:Readonly<User> = {
firstName: "John",
lastName: "Doe"
}
If you try to change a property of firstUser
, you'll get the following error:
Cannot assign to 'firstName' because it is a read-only property.
Readonly Variables Don’t Work in Typescript
When we define the type User
above, we are creating a custom interface - i.e. something to which objects have to conform to. Readonly only works with interfaces or custom types like the one we've used. As such, we can still edit Readonly
variables:
let myVariable:Readonly<string> = "Hello World";
myVariable = "Goodbye World";
console.log(myVariable); // console logs "Goodbye World"
The above code is valid and will work in TypeScript. If you need read-only variables, you can simply use const instead, i.e:
const myVariable:string = "Hello World";
// Throws error: Cannot assign to 'myVariable' because it is a constant.
myVariable = "Goodbye World";
Published at DZone with permission of Johnny Simpson, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments