TypeScript Readonly Property

TypeScript allows us to make an individual property readonly. When we use readonly, we can’t assign them with other variables, can’t update or delete. This avoids unexpected mutation.

Let’s write an example.

let students: readonly Array<string> = ["John", "Michael", "Adam"]

If we try to assign students array with a new array type property.

let good_students: Array<string> = students

We can get an error message.

The type ‘readonly string[]’ is ‘readonly’ and cannot be assigned to the mutable type ‘string[]’.

That means the readonly string array can’t be assigned to another string array.

readonly in Tuple Type

Just like array we can make Tuple readonly.

let results: readonly [number, number] = [10, 20]

If we try to mutate the results, we will get error.

results[0] = 50// error

results.push(100)// error

results.pop()// error

Leave a Comment

Your email address will not be published. Required fields are marked *