TypeScript · Junior · Question 8 of 75

What does the readonly modifier do in { readonly id: number }?

Explanation

readonly is just a compiler check: obj.id = 2 causes an error. It's shallow - nested objects can be changed. At runtime the object is ordinary. For arrays there's readonly string[] / ReadonlyArray<string>, and deep freezing is done with as const or Object.freeze.

Further reading

Problem with a question

TypeScript · Junior · question 8

Test yourself

Take the TypeScript · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz