← Back to TypeScript Course | Chapter 8: Advanced Types | Lesson 12 of 20

Utility Types में Readonly

Readonly<T> एक object type की हर property को readonly बनाता है। यह initialization के बाद उन properties के reassignment को रोकता है।
Syntax
typescript
type Result = Readonly<TypeName>;

Basic Readonly

Readonly<T> एक object type का एक version produce करता है जिसकी properties अब reassign नहीं हो सकतीं, वही compile-time protection देते हुए जो हर property पर हाथ से readonly modifier लिखने से मिलती है।

उदाहरण: Basic Readonly

typescript
interface Point {
  x: number;
  y: number;
}
const p: Readonly<Point> = { x: 1, y: 2 };
console.log(p);

Readonly Arrays

Readonly array types पर भी apply हो सकता है push, pop, या splice जैसे methods से mutation रोकने के लिए, जबकि array के existing elements को freely read होने देते हुए।

उदाहरण: Readonly Arrays

typescript
const values: ReadonlyArray<number> = [1, 2, 3];
console.log(values[0]);

Readonly Objects

Readonly उन objects के लिए उपयोगी है जिन्हें fixed configuration या reference data के रूप में treat किया जाना चाहिए — values जो program के lifetime में पढ़ी जानी चाहिए लेकिन creation के बाद कभी modify नहीं होनी चाहिए।

उदाहरण: Readonly Objects

typescript
interface AppConfig {
  apiUrl: string;
}
const config: Readonly<AppConfig> = { apiUrl: "https://api.example.com" };
console.log(config.apiUrl);

Readonly and Nested Objects

Readonly सिर्फ एक object की top-level properties पर apply होता है; इसके अंदर मौजूद किसी भी nested objects को अगर उनकी properties भी protect करनी हों तो अपनी अलग Readonly wrapping चाहिए।

उदाहरण: Readonly and Nested Objects

typescript
interface Address {
  city: string;
}
interface Person {
  name: string;
  address: Address;
}
const p: Readonly<Person> = { name: "Ravi", address: { city: "Patna" } };
p.address.city = "Delhi";
console.log(p.address.city);

When to Use Readonly

Readonly<T> उपयोगी है जब भी callers को data freely inspect करने में सक्षम होना चाहिए लेकिन इसकी properties कभी reassign नहीं करनी चाहिए, जो accidental shared-state bugs रोकने में मदद करता है।

उदाहरण: When to Use Readonly

typescript
interface Constants {
  PI: number;
}
const MATH: Readonly<Constants> = { PI: 3.14159 };
console.log(MATH.PI);
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह सोचना कि Readonly<T> object को runtime पर freeze करता है, जब यह सिर्फ compiler द्वारा check होता है।
  2. Readonly के nested objects protect करने की उम्मीद करना, जब p.address.city = "x" अब भी allowed है।
  3. एक ReadonlyArray<number> पर push call करना, जो उस type पर मौजूद नहीं है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.