TypeScript Course
TypeScript
/
Intermediate

Readonly Properties

Definition

The `readonly` modifier makes an object property or an entire array immutable in TypeScript, preventing reassignment after initialization.

Explain Like I'm New

If an object is a museum exhibit, `readonly` is the 'Do Not Touch' glass case around a specific artifact. You can look at it, but the compiler will throw an error if you try to change its value.

Real World Example

Database IDs. When you fetch a user from the DB, their `id` shouldn't change. `type User = { readonly id: number; name: string }`.

Common Use Cases

  • •Preventing accidental mutation
  • •Redux state definitions
  • •Functional programming patterns

Interactive Example

interface Configuration {
  readonly apiKey: string;
  theme: string;
}

const myConfig: Configuration = {
  apiKey: "12345-ABCDE",
  theme: "dark"
};

myConfig.theme = "light"; // Allowed
// myConfig.apiKey = "999"; // ERROR: Cannot assign to 'apiKey' because it is a read-only property.

// Readonly Arrays
const strictList: readonly number[] = [1, 2, 3];
// strictList.push(4); // ERROR: Property 'push' does not exist on type 'readonly number[]'.

Interview Questions

basic

  • How do you make a property readonly?

intermediate

  • Is `readonly` enforced at runtime in the browser?

advanced

  • What is the difference between `readonly string[]` and `ReadonlyArray<string>`?

Flash Cards

Question

Is it enforced at runtime?

Click to reveal answer
Answer

No. Like almost all TypeScript features, it is erased during compilation. It only prevents you from mutating it IN YOUR CODE EDITOR. If a 3rd party script mutates the object at runtime, the browser won't stop it.

Question

Difference between readonly [] and ReadonlyArray?

Click to reveal answer
Answer

There is no difference, they are just different syntaxes for the exact same thing. A Readonly array removes mutating methods like `.push()`, `.pop()`, and `.splice()`.