Utility Types में Readonly
In this page:
type Result = Readonly<TypeName>;
Basic Readonly
Readonly<T> एक object type का एक version produce करता है जिसकी properties अब reassign नहीं हो सकतीं, वही compile-time protection देते हुए जो हर property पर हाथ से readonly modifier लिखने से मिलती है।
उदाहरण: Basic Readonly
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
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
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
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
interface Constants {
PI: number;
}
const MATH: Readonly<Constants> = { PI: 3.14159 };
console.log(MATH.PI);
- यह सोचना कि
Readonly<T>object को runtime पर freeze करता है, जब यह सिर्फ compiler द्वारा check होता है। - Readonly के nested objects protect करने की उम्मीद करना, जब
p.address.city = "x"अब भी allowed है। - एक
ReadonlyArray<number>परpushcall करना, जो उस type पर मौजूद नहीं है।
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- TypeScript Advanced Types
- Mapped Types
- Conditional Types
- Custom Type Guards
- Assertion Functions
- Control Flow Analysis
- Exhaustiveness Checking
- Satisfies Operator
- Template Literal Types
- Utility Types - Partial
- Utility Types - Required
- Utility Types - Readonly
- Utility Types - Pick
- Utility Types - Omit
- Utility Types - Record
- Utility Types - Exclude and Extract
- Utility Types - NonNullable
- Utility Types - ReturnType
- Utility Types - Parameters
- TypeScript 5 Updates