Course contentsShow
← TypeScript
Lesson 304 of 1,7967. ObjectsFree lesson

Readonly at Compile Time Only

Understand that readonly is a TypeScript feature with no runtime enforcement.

Readonly at Compile Time Only

What you'll learn: You'll understand that TypeScript's readonly modifier only prevents modifications during development and disappears completely when your code runs.

The Compile-Time Safety Net

When you mark a property as readonly in TypeScript, you're adding a compile-time guard rail, not a runtime lock. Think of it like a safety warning painted on the floor of a warehouse — it guides careful workers during the day, but once the lights go out (when JavaScript runs), the paint provides zero physical protection.

TypeScript's readonly modifier exists only in your .ts files. When TypeScript compiles to JavaScript, all type information — including readonly — is completely erased. The resulting JavaScript code has no memory that a property was ever marked readonly.

Why This Matters

type User = {
  readonly id: number;
  name: string;
};

const user: User = { id: 1, name: "Alice" };

// TypeScript error: Cannot assign to 'id' because it is a read-only property
// user.id = 2;

This code will error in your editor and when running tsc. But if someone bypasses TypeScript (using any, or consuming your compiled JavaScript directly), they can modify id freely:

const user: User = { id: 1, name: "Alice" };
(user as any).id = 999; // Compiles and runs successfully

After compilation, the JavaScript looks like ordinary object manipulation — there's no runtime enforcement mechanism built into JavaScript itself.

The Takeaway

readonly is a development-time tool for catching mistakes in your TypeScript code. It won't protect your data from modification once the code runs as JavaScript. If you need true runtime immutability, you must use JavaScript features like Object.freeze().

Key Takeaway: The readonly modifier only exists during TypeScript compilation — it provides zero runtime protection and disappears entirely in the final JavaScript output.