DEV Community

Cover image for React+ Typescript: Deep Dive into "readonly"
Arka Chakraborty
Arka Chakraborty

Posted on

React+ Typescript: Deep Dive into "readonly"

Type-Level Immutability in TypeScript with readonly


đź’ˇIntro

When you want to make sure no one mutates your types, readonly is your tool.


đź§ Context

Unlike as const, which applies at the value level, readonly applies immutability at the type level. It prevents accidental mutations in objects, arrays, and class properties.


📌Intro

In React apps, readonly ensures props, API response types, and shared objects remain untouched.


❓Why Use This?

  • Prevents runtime bugs by forbidding mutation.
  • Useful for API response modeling.
  • Guarantees immutability in large codebases.

📝With vs Without Example

// Without readonly interface User { name: string; age: number; } let user: User = { name: "Arka", age: 22 }; user.age = 23; // Allowed 
Enter fullscreen mode Exit fullscreen mode
// With readonly interface User { readonly name: string; readonly age: number; } let user: User = { name: "Arka", age: 22 }; user.age = 23; // Error: cannot assign 
Enter fullscreen mode Exit fullscreen mode

📌Real Life Use Cases

React Props

type ProfileProps = { readonly name: string; readonly skills: readonly string[]; }; function Profile({ name, skills }: ProfileProps) { // Cannot mutate skills inside return <div>{skills.join(", ")}</div>; } 
Enter fullscreen mode Exit fullscreen mode

API Response

type ApiResponse = { readonly id: number; readonly status: "success" | "error"; }; 
Enter fullscreen mode Exit fullscreen mode

readonly ensures compile-time safety. It does not make runtime data truly immutable, it just prevents mutation in code.

Top comments (0)