Readonly के Best Practices
In this page:
interface TypeName {
readonly propertyName: type;
}
const list: readonly type[] = [item1, item2];
const tuple: readonly [type, type] = [a, b];
Readonly Properties
एक property को readonly मार्क करें जब यह genuinely object construct होने के बाद कभी reassign नहीं होनी चाहिए — यह identifiers, timestamps, और configuration values के लिए खासकर valuable है जिन्हें एक बार set होना होता है।
उदाहरण: Readonly Properties
interface User {
readonly id: number;
name: string;
}
const user: User = { id: 1, name: "Ravi" };
user.name = "Updated";
console.log(user);
Readonly Arrays
एक readonly array type compile time पर push या pop जैसे किसी भी method को block करता है जो array को in place mutate करे — जब भी एक function को सिर्फ एक collection पढ़नी हो, कभी modify नहीं करनी, इसकी ओर पहुंचें।
उदाहरण: Readonly Arrays
function printAll(items: readonly string[]) {
console.log(items.join(", "));
}
printAll(["a", "b", "c"]);
Readonly Tuples
readonly tuples tuple की fixed length और इसके readonly behavior दोनों को साथ preserve करते हैं, जो coordinates, key-value pairs, और दूसरे छोटे, fixed-position data के लिए naturally fit होता है जिन्हें resize या mutate नहीं होना चाहिए।
उदाहरण: Readonly Tuples
const point: readonly [number, number] = [10, 20];
console.log(point[0], point[1]);
Readonly Parameters
Function parameters पर readonly उपयोग करें जब वह function इसके caller द्वारा pass किए किसी object या collection को mutate न करे — यह function के contract को एक comment में सिर्फ नहीं बल्कि सीधे type level पर document करता है।
उदाहरण: Readonly Parameters
function sum(numbers: readonly number[]): number {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum([1, 2, 3]));
Readonly Deep Immutability नहीं है
readonly सिर्फ property या collection reference को खुद protect करता है — यह nested objects को भी अपने आप immutable नहीं बनाता, इसलिए readonly को recursively apply करें (या एक dedicated deep-immutability type) जब यह असल में चाहिए।
उदाहरण: Readonly Is Not Deep Immutability
interface Address { city: string; }
interface User { readonly address: Address; }
const user: User = { address: { city: "Patna" } };
user.address.city = "Delhi"; // allowed -- readonly is shallow
console.log(user.address.city);
- हर property को
readonlyमार्क करना उन properties सहित जिनको बदलना है, फिर casts से इसके around काम करना। - यह मान लेना कि
readonlyobject के अंदर nested objects और arrays को protect करता है। - एक parameter पर
readonlyउपयोग करना और फिर भी इस परpushcall करना, जो एक compile error है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: