एक enum ले नाम भएका constants को एक समूह परिभाषित गर्छ। TypeScript मा numeric र string enums छन्।
{ , , , }
.;
[];
{
= ,
= ,
}
.;
एक enum ले नाम भएका constants को एक समूह परिभाषित गर्छ। TypeScript मा numeric र string enums छन्।
{ , , , }
.;
[];
{
= ,
= ,
}
.;
अधिकांश TypeScript types (जो compile समयमा हराउँछन्) को विपरीत, एक regular enum ले तपाईको bundle मा एक JavaScript object emit गर्छ। यसैले धेरै teams ले string literals को union र as const लाई प्राथमिकता दिन्छन्, जो विशुद्ध type-level छ:
// often preferred — zero runtime cost, easy to read in logs
const Status = { Active: "ACTIVE", Inactive: "INACTIVE" } as const;
type Status = typeof Status[keyof typeof Status]; // "ACTIVE" | "INACTIVE"
// or simply:
type Direction = "up" | "down" | "left" | "right";
const enum E { A, B } // inlined at compile time — no runtime object, but has tooling caveats
Enums ले fixed sets (states, roles, directions) लाई अर्थपूर्ण नामहरू दिन्छ र तिनलाई एक namespace अन्तर्गत समूहबद्ध गर्छ।
तर किनभने तिनीहरूले runtime code emit गर्छन् र विचित्र गुणहरू छन् (numeric enums ढिलो रूपमा जाँच गरिन्छ), आधुनिक TypeScript अक्सर साधारण केसहरूको लागि string-literal unions लाई प्राथमिकता दिन्छ — तिनीहरू हल्का र naturally serialize हुन्छन्।
Enums प्रयोग गर्नुहोस् जब तपाईले namespacing वा reverse mapping चाहनुहुन्छ।