Type Aliases aur Union Types
Ek type alias kisi bhi type ko ek naam deta hai, taake aap same shape har jagah dohrane ke bajaye usko reuse kar sakein. 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 ke ek value listed types mein se koi bhi ek ho sakti hai. Yeh TypeScript ka woh tareeqa hai jisse "yeh waqai dono kism ki value ho sakti hai" zaahir hota hai, type safety khoye baghair.
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 khaas literal value bhi ho sakta hai — literals ka union woh tareeqa hai jisse TypeScript "in options mein se bilkul koi ek" zaahir 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.