Type के Aliases
In this page:
type AliasName = type;
type ObjectAlias = {
property: type;
};
Creating a Type Alias
type keyword, एक नाम और एक equals sign के बाद, एक type alias define करता है, जैसे type ID = string | number। Alias फिर कहीं भी उपयोग हो सकता है जहां आप normally original type लिखते, repeated या complex types को readable और consistent रखते हुए।
उदाहरण: Creating a Type Alias
type ID = string | number;
let userId: ID = 42;
userId = "abc";
console.log(userId);
Object Type Aliases
एक type alias एक object की structure describe कर सकता है, इस purpose के लिए बहुत कुछ एक interface जैसा काम करते हुए। यह तब उपयोगी है जब codebase में कई variables या functions को exact same set की properties share करने वाले objects के साथ काम करना हो।
उदाहरण: Object Type Aliases
type User = {
name: string;
age: number;
};
const user: User = { name: "Tia", age: 29 };
console.log(user);
Type Aliases for Functions
एक type alias एक function की पूरी signature describe कर सकता है, इसके parameter types और return type दोनों को एक reusable नाम में capture करते हुए। यह function types को pass around करना, variables में store करना आसान बनाता है, और उन्हें उपयोग करने वाली function declarations को पढ़ना काफी आसान रखता है।
उदाहरण: Type Aliases for Functions
type MathOp = (a: number, b: number) => number;
const add: MathOp = (a, b) => a + b;
console.log(add(2, 3));
Combining Type Aliases
Type aliases को दूसरे types के साथ combine किया जा सकता है, सबसे commonly unions या intersections के through, छोटे, reusable pieces से ज़्यादा expressive structures बनाने के लिए।
यह एक giant inline type लिखने के बजाय बड़े types को compositionally बनाने को encourage करता है।
उदाहरण: Combining Type Aliases
type Timestamped = { createdAt: string };
type Named = { name: string };
type Record = Timestamped & Named;
const record: Record = { createdAt: "2024", name: "Log" };
console.log(record);
Reusable Domain Types
Type aliases एक application में core domain concepts को नाम देने के लिए खासकर valuable हैं, जैसे User, Product, Order, या एक specific configuration shape।
जहां भी वे concepts दिखें वहां एक single named alias reuse करना related code को consistent और एक जगह update करना आसान रखता है।
उदाहरण: Reusable Domain Types
type Product = {
id: number;
name: string;
price: number;
};
function printProduct(p: Product) {
console.log(`${p.name}: $${p.price}`);
}
printProduct({ id: 1, name: "Pen", price: 2 });
type ID = string | numberउपयोग करना और फिर value को string मान लेना बिना narrowing के।- एक ही type alias को दो बार redeclare करने की कोशिश करना, जो एक error है।
- यह सोचना कि एक type alias एक नई runtime value या एक distinct type बनाता है, जब यह सिर्फ एक और नाम है।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: