enum అనేది పేర్కొన్న స్థిరాంకాల సమితిని నిర్వచిస్తుంది. TypeScript లో సంఖ్యా enums మరియు string enums ఉన్నాయి.
{ , , , }
.;
[];
{
= ,
= ,
}
.;
enum అనేది పేర్కొన్న స్థిరాంకాల సమితిని నిర్వచిస్తుంది. TypeScript లో సంఖ్యా enums మరియు string enums ఉన్నాయి.
{ , , , }
.;
[];
{
= ,
= ,
}
.;
Best of TypeScript రకాలు (ఇవి కంపైల్ సమయంలో అదృశ్యమవుతాయి) కాకుండా, సాధారణ enum మీ బండిల్కు JavaScript ఆబ్జెక్ట్ను విడుదల చేస్తుంది. అందుకే చాలా గループ్లు 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 స్థిర సమితులకు (states, roles, directions) అర్థవంతమైన పేర్లను ఇస్తాయి మరియు వాటిని ఒకే namespace కింద సమూహం చేస్తాయి.
కానీ రన్టైమ్ కోడ్ను విడుదల చేయడం మరియు బేసిబిలిటీలను కలిగి ఉండటం కారణంగా (సంఖ్యా enums느슨하게తనిఖీ చేయబడతాయి), ఆధునిక TypeScript తరచుగా సాధారణ సందర్భాలకు string-literal unions కోసం ఇష్టపడుతుంది — అవి తేలికైనవి మరియు సహజంగా సీరియలైజ్ చేస్తాయి.
నామ్స్పేసింగ్ లేదా రివర్స్ మ్యాపింగ్ కోసం enums ఉపయోగించండి.