Type Aliases aur Union Types
Ek type alias kisi bhi type ko ek naam deta hai, taaki aap same shape har jagah repeat karne ke bajaye usko reuse kar sako. Yeh objects describe karne ke liye functionally interface jaisa hi hai, lekin type un cheezon ko bhi naam de sakta hai jo interface nahi de sakta, jaise unions.
type Point2D = { x: number; y: number };
let home: Point2D = { x: 0, y: 0 };
console.log(home);{ x: 0, y: 0 }Union types — ek value jo kai types mein se ek ho sakti hai
Ek union type, jo | se likha jaata hai, ka matlab hai ki ek value listed types mein se koi bhi ek ho sakti hai. Yeh TypeScript ka woh tarika hai jisse "yeh genuinely dono kism ki value ho sakti hai" express hota hai, type safety khoye bina.
function formatId(id: string | number): string {
return `ID-${id}`;
}
console.log(formatId(42));
console.log(formatId("A17"));ID-42 ID-A17
Literal types
Ek type poori category ke bajaye ek specific literal value bhi ho sakta hai — literals ka union woh tarika hai jisse TypeScript "in options mein se bilkul koi ek" express karta hai, ek enum jaisa hi lekin halka.
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
move("up");
move("left");Moving up Moving left
Aage: functions — typed parameters, return types, aur optional aur default parameters.