Tuple के Types
In this page:
let tuple: [type1, type2] = [value1, value2];
Basic Tuple
एक tuple type एक fixed-length array में हर position का exact type define करता है, जैसे एक name को age के साथ pair करने के लिए [string, number]।
एक regular array type के विपरीत, order और count of types मायने रखते हैं, सिर्फ यह नहीं कि collection में कहीं कौन से types allowed हैं।
उदाहरण: Basic Tuple
let person: [string, number] = ["Aisha", 30];
console.log(person);
Tuple Values Access करना
Tuple elements को एक regular array जैसे ही उनके numeric indexes उपयोग करके access किया जा सकता है, लेकिन TypeScript को हर position पर expected specific type पहले से पता है।
इसका मतलब है tuple[0] को string और tuple[1] को number पता है, बिना किसी manual casting के।
उदाहरण: Accessing Tuple Values
let person: [string, number] = ["Kiran", 28];
console.log(person[0], person[1]);
Tuple Destructuring
Tuple values को array destructuring उपयोग करके अलग named variables में unpack किया जा सकता है, उदाहरण के लिए const [name, age] = person। Resulting variables के types उनके corresponding tuple positions से automatically infer होते हैं।
उदाहरण: Tuple Destructuring
const person: [string, number] = ["Divya", 22];
const [name, age] = person;
console.log(name, age);
Optional Tuple Elements
Tuple elements को उनके type के बाद एक question mark जोड़कर optional मार्क किया जा सकता है, जैसे [string, number?]। Optional elements को हमेशा हर required element के बाद ही आना चाहिए, क्योंकि उनकी position अब भी predictable होनी चाहिए।
उदाहरण: Optional Tuple Elements
let entry: [string, number?] = ["Rahul"];
console.log(entry);
entry = ["Meera", 5];
console.log(entry);
Readonly Tuples
एक readonly tuple, readonly [string, number] के रूप में लिखा गया, tuple बनने के बाद किसी भी element को reassign होने से रोकता है।
यह values की एक fixed, immutable pairing represent करने के लिए useful है, जैसे एक coordinate जो कभी in place mutate नहीं होना चाहिए।
उदाहरण: Readonly Tuples
let point: readonly [number, number] = [10, 20];
// point[0] = 99; // rejected: readonly tuples block reassignment
console.log(point);
- जब हर type की position मायने रखे तब plain array type
(string | number)[]उपयोग करना, इसलिए[30, "Aisha"]reject नहीं होता। - एक
[string, number]tuple में एक extra element जोड़ना जैसे["Aisha", 30, true], जो fail होता है क्योंकि length fixed है। - एक required element से पहले एक tuple element को optional मार्क करना, जैसे
[string?, number], जो allowed नहीं है।
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: