Array के Types
In this page:
let items: type[] = [value1, value2];
let items2: Array<type> = [value1, value2];
Basic Array Syntax
आप type[] syntax उपयोग करके एक array declare कर सकते हैं, जैसे strings के array के लिए string[] या numbers के array के लिए number[]। उस array में push की गई या store की गई हर value specified type से match होनी चाहिए, या compiler इसे flag करता है।
उदाहरण: Basic Array Syntax
let names: string[] = ["Amit", "Priya"];
let nums: number[] = [1, 2, 3];
console.log(names, nums);
Array Methods
Typed arrays हर normal JavaScript array method support करती हैं, जैसे push, pop, map, और filter, exactly पहले जैसे। अंतर यह है कि TypeScript उन methods को pass की गई values जांचती है, इसलिए एक string[] array में एक number push करना तुरंत पकड़ा जाता है।
उदाहरण: Array Methods
let nums: number[] = [1, 2, 3];
nums.push(4);
// nums.push("five"); // rejected: string is not a number
console.log(nums.map(n => n * 2));
Alternative Array Syntax
TypeScript Type[] के alternative के रूप में generic Array<Type> syntax भी support करती है, और दोनों का exactly वही मतलब है। Generic form कभी-कभी readability के लिए preferred होता है जब element type खुद पहले से एक complex generic type हो।
उदाहरण: Alternative Array Syntax
let names: Array<string> = ["Kabir", "Neha"];
console.log(names);
Readonly Arrays
एक readonly array, readonly Type[] के रूप में लिखा गया, values को normally पढ़ने देता है लेकिन push या splice जैसे किसी भी mutate करने वाले method को block करता है।
यह उन function parameters के लिए useful है जहां आप guarantee करना चाहते हैं कि caller का array गलती से modify न हो।
उदाहरण: Readonly Arrays
let ids: readonly number[] = [1, 2, 3];
// ids.push(4); // rejected: readonly arrays block mutation
console.log(ids);
Objects के Arrays
Arrays में एक defined shape वाले objects हो सकते हैं, जहां एक interface या object type उन properties describe करता है जो array में हर item के पास होनी चाहिए। यह TypeScript को उनमें से एक बड़े array में किसी एक object पर property name में typo पकड़ने देता है।
उदाहरण: Arrays of Objects
interface Product {
name: string;
price: number;
}
let products: Product[] = [{ name: "Pen", price: 2 }, { name: "Book", price: 8 }];
console.log(products);
let nums: number[] = [1, 2, "3"]लिखना, ऐसे types mix करना जिन्हें array type allow नहीं करता।- बिना type के
let items = []declare करना औरstring[]याnumber[]के बजाय एक implicitany[]मिलना। - एक
readonly number[]परpushcall करना, जो एक compile error है क्योंकि array read-only है।
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: