AnyCompiler

Array Methods: map, filter, aur reduce

map() aur filter() bilkul JavaScript ki tarah kaam karte hain, lekin TypeScript transformation ke through type ko track karta hai — ek number[] ko ek aise function se map karo jo string return karta hai, aur result string[] ke roop mein infer ho jaata hai, koi annotation ki zaroorat nahi.

const numbers: number[] = [1, 2, 3, 4, 5];
const squared = numbers.map((x) => x * x);
console.log(squared);

const evens = numbers.filter((x) => x % 2 === 0);
console.log(evens);
Output
[ 1, 4, 9, 16, 25 ]
[ 2, 4 ]

reduce — har item ko ek value mein combine karna

reduce() ek accumulator ko ek item se doosre tak carry karta hai. TypeScript accumulator ka type us starting value se infer karta hai jo aap dete ho.

const numbers: number[] = [1, 2, 3, 4, 5];
const total = numbers.reduce((sum, x) => sum + x, 0);
console.log(total);
Output
15

Aage: exception handling — errors ko catch karna, aur ek caught error unknown type ka kyun hota hai, any nahi.