DEV Community

Cover image for How the TypeScript Readonly Type Works
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

How the TypeScript Readonly Type Works

TypeScript 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"
}
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Readonly variables don't work in TypeScript

When we define the type User above, we are creating a custom interface - i.e. something 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"
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

Discussion (0)