Readonly Properties की जानकारी
In this page:
interface InterfaceName {
readonly property: type;
}
Declaring Readonly Properties
एक interface के अंदर किसी property से पहले readonly रखना, जैसे readonly id: number, object बनने के बाद उस property को directly reassign होने से रोकता है।
Object की initial creation के बाहर इसे write करने की कोई भी कोशिश एक compile-time error produce करती है।
उदाहरण: Declaring Readonly Properties
interface Item {
readonly id: number;
name: string;
}
const item: Item = { id: 1, name: "Widget" };
// item.id = 2; // rejected: id is readonly
console.log(item);
Readonly and Object Creation
Readonly properties को object बनने के moment ही उनकी initial value मिलती है और उसके बाद fixed रहने की उम्मीद होती है। यह एक database ID या एक creation timestamp जैसी values के लिए ideal है जिन्हें object के lifetime के दौरान legitimately कभी नहीं बदलना चाहिए।
उदाहरण: Readonly and Object Creation
interface Record {
readonly createdAt: string;
}
const record: Record = { createdAt: "2024-01-01" };
console.log(record.createdAt);
Readonly Arrays
एक readonly array type, जो readonly number[] के रूप में लिखी जाती है, push, pop, या splice जैसे किसी भी mutating method को इस पर call होने से रोकती है, और direct index assignment को भी block करती है।
यह एक compile-time guarantee है कि एक given array reference उस variable के through modify नहीं होगा।
उदाहरण: Readonly Arrays
const ids: readonly number[] = [1, 2, 3];
// ids.push(4); // rejected: readonly arrays block mutation
console.log(ids);
Readonly Does Not Mean Deeply Immutable
यह जानना important है कि readonly सिर्फ उस property को protect करता है जिस पर यह directly apply होता है; अगर वह property एक nested object रखती है, तो nested object की अपनी properties automatically immutable नहीं बनती हैं।
Deep immutability के लिए readonly को recursively apply करना या एक dedicated utility type उपयोग करना चाहिए।
उदाहरण: Readonly Does Not Mean Deeply Immutable
interface Wrapper {
readonly data: { count: number };
}
const wrapper: Wrapper = { data: { count: 1 } };
wrapper.data.count = 99; // allowed: nested object isn't protected
console.log(wrapper.data.count);
Readonly with Functions
Readonly properties उन functions के लिए खासकर उपयोगी हैं जिन्हें important values को गलती से बदले बिना पढ़ना है, जैसे एक function जो किसी object की state पर report करता है पर उसे mutate करने की permission नहीं है।
यह एक easy-to-miss bug को एक compiler error में बदल देता है।
उदाहरण: Readonly with Functions
interface Point {
readonly x: number;
readonly y: number;
}
function report(point: Point): string {
return `(${point.x}, ${point.y})`;
}
console.log(report({ x: 3, y: 4 }));
- एक
readonlyproperty को assign करना जैसेitem.id = 2, जो एक compile error है। - यह मान लेना कि
readonlynested objects को protect करता है, जब सिर्फ वह property खुद locked होती है। - यह उम्मीद करना कि
readonlyruntime पर enforce होता है, जब यह सिर्फ type system में मौजूद है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: