Readonly Members की जानकारी
In this page:
class ClassName {
readonly property: type;
constructor(value: type) {
this.property = value;
}
}
Readonly Properties
एक readonly property को declare होने पर या constructor में initialize होने पर assign किया जा सकता है, लेकिन उस point के बाद की गई कोई भी assignment compile time पर reject होती है, class के अंदर से भी।
उदाहरण: Readonly Properties
class Config {
readonly version: string = "1.0";
}
const config = new Config();
// config.version = "2.0"; // rejected: readonly
console.log(config.version);
Constructors के साथ Readonly
Readonly properties को अक्सर constructor parameters के through initialize किया जाता है, जो एक ID या creation timestamp जैसी values के लिए उपयोगी है जो object के पूरे lifetime के लिए fixed होनी चाहिए।
उदाहरण: Readonly with Constructors
class User {
readonly id: number;
constructor(id: number) {
this.id = id; // allowed: assigned inside the constructor
}
}
console.log(new User(101).id);
Readonly Arrays
TypeScript readonly array types भी प्रदान करता है; एक readonly array को push या splice जैसे mutating methods से modify नहीं किया जा सकता, हालांकि एक नया array अब भी produce और कहीं और assign किया जा सकता है।
उदाहरण: Readonly Arrays
const tags: readonly string[] = ["ts", "types"];
// tags.push("more"); // rejected: readonly arrays block mutation
console.log(tags);
Readonly Method Access
Readonly एक property को assignment पर affect करता है, इसे पढ़ने पर नहीं — code freely एक readonly value पढ़ और पास कर सकता है, TypeScript सिर्फ इसमें एक नई value लिखने की specific act को block करता है।
उदाहरण: Readonly Method Access
class Point {
constructor(public readonly x: number) {}
}
const p = new Point(5);
console.log(p.x * 2); // reading is fine
Readonly कब उपयोग करें
Readonly identifiers, creation dates, configuration values, और दूसरे data के लिए appropriate है जिसे object बनने के बाद legitimately कभी नहीं बदलना चाहिए, क्योंकि यह एक accidental mutation को एक subtle runtime bug के बजाय एक compile-time error बना देता है।
उदाहरण: When to Use Readonly
class Event {
readonly createdAt: Date = new Date();
}
console.log(new Event().createdAt instanceof Date);
- एक
readonlyproperty को constructor के बाहर assign करना, जैसेconfig.version = "2.0", जो एक compile error है। - यह मान लेना कि
readonlyएक object को deeply immutable बना देता है, जबreadonly tags: string[]अब भी array पर हीtags.push("x")allow करता है। - यह उम्मीद करना कि
readonlyruntime पर enforce किया जाएगा, जब यह erased हो जाता है और plain JavaScript अब भी value को overwrite कर सकता है।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: