TypeScript के Object Types
In this page:
let obj: { property: type; optional?: type } = {
property: value,
};
Basic Object Types
एक object type literal property names और उनके types को directly annotation में list करता है, जैसे { name: string; age: number }, TypeScript को एक separate interface या type alias declare किए बिना यह check करने देते हुए कि एक value exactly described shape रखती है।
उदाहरण: Basic Object Types
let user: { name: string; age: number } = { name: "Neha", age: 28 };
console.log(user);
Optional Properties
एक property name के बाद एक question mark जोड़ना, जैसे darkMode?: boolean, इसे optional मार्क करता है ताकि एक matching value उस property को पूरी तरह omit कर सके, और TypeScript property access होने पर इसके type को undefined शामिल मानता है।
उदाहरण: Optional Properties
let settings: { darkMode?: boolean } = {};
console.log(settings.darkMode); // undefined, since darkMode was omitted
settings = { darkMode: true };
console.log(settings.darkMode);
Readonly Properties
एक property के आगे readonly लगाना इसे object बनने के बाद reassign होने से रोकता है, जो identifiers या coordinates जैसी values के लिए useful है जो set होने के बाद कभी नहीं बदलनी चाहिए, जबकि उसी object की दूसरी properties अब भी normally update हो सकती हैं।
उदाहरण: Readonly Properties
let point: { readonly x: number; y: number } = { x: 5, y: 10 };
// point.x = 99; // rejected: x is readonly
point.y = 20;
console.log(point);
Object Types में Index Signatures
[key: string]: number जैसा एक index signature एक object type को किसी भी number of properties accept करने देता है जिनके नाम पहले से नहीं पता, जब तक हर value declared type से match करे, जो dictionaries और lookup tables के लिए useful है।
उदाहरण: Index Signatures in Object Types
let scores: { [key: string]: number } = {};
scores["math"] = 90;
scores["science"] = 85;
console.log(scores);
Nested Object Types
Object types अपनी property values के रूप में दूसरे object types nest कर सकते हैं, इसलिए { address: { city: string; zip: string } } जैसा एक type कई levels वाला structured data describe करता है, और हर nested property उतनी ही strictness से check होती है जितना एक top-level property।
उदाहरण: Nested Object Types
let profile: { address: { city: string; zip: string } } = {
address: { city: "Pune", zip: "411001" },
};
console.log(profile.address.city);
{ name: "Neha", age: 28, city: "Delhi" }जैसे एक object literal में एक extra property जोड़ना, जो excess property error trigger करता है।settings.darkModeजैसी एक optional property पढ़ना और यह भूल जाना कि यहundefinedहो सकती है।- एक
readonlyproperty को creation के बाद assign करना और इसके work करने की उम्मीद करना, जबreadonlycompile time पर ही इसे रोकता है।
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: