Enum के Types
In this page:
enum EnumName {
Member1,
Member2,
Member3,
}
Numeric Enums
एक numeric enum अपने हर member को एक numeric value assign करता है, और by default पहला member zero से शुरू होता है हर बाद वाला member automatically increment होते हुए। आप starting value explicitly भी set कर सकते हैं, और बाकी वहां से count up करेंगे।
उदाहरण: Numeric Enums
enum Direction {
Up,
Down,
Left,
Right,
}
console.log(Direction.Up, Direction.Right);
String Enums
String enums अपने हर member को एक auto-incrementing number के बजाय एक explicit string value देते हैं, enum definition में directly लिखी गई।
वे debug करने में अक्सर आसान होती हैं क्योंकि value को log या serialize करना एक opaque number के बजाय एक meaningful word दिखाता है।
उदाहरण: String Enums
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
}
console.log(Status.Active);
Functions में Enums उपयोग करना
Enums directly एक function parameter के type के रूप में उपयोग किए जा सकते हैं, जो callers को सिर्फ उस enum में actually defined values तक restrict करता है।
यह एक caller को एक arbitrary number या string pass करने से रोकता है जहां सिर्फ known, fixed set of options में से एक sense बनाता है।
उदाहरण: Using Enums in Functions
enum Role {
Admin,
Editor,
Viewer,
}
function checkAccess(role: Role): void {
console.log(`Access level: ${Role[role]}`);
}
checkAccess(Role.Admin);
Enum Comparisons
Enum members को normal equality operators उपयोग करके compare किया जा सकता है, बिल्कुल किसी और value की तरह, क्योंकि हर member असल में सिर्फ एक constant है under the hood। यह program behavior को branch करना आसान बनाता है इस आधार पर कि अभी कौन सी known enum value held है।
उदाहरण: Enum Comparisons
enum Status {
Active,
Inactive,
}
let current: Status = Status.Active;
console.log(current === Status.Active);
Switch Statements में Enums
Enums switch statements के साथ खासतौर पर अच्छे से pair होते हैं, क्योंकि हर case label exactly एक known enum member represent कर सकता है। यह code को organized रखता है जिसे कई distinct states handle करने हों और एक नज़र में देखना आसान बनाता है कि क्या हर option covered है।
उदाहरण: Enums in Switch Statements
enum Status {
Active,
Inactive,
Pending,
}
let current: Status = Status.Pending;
switch (current) {
case Status.Active:
console.log("Active");
break;
case Status.Pending:
console.log("Pending");
break;
default:
console.log("Other");
}
- यह assume करना कि numeric enum values 1 से शुरू होती हैं, जब पहला member
0होता है जब तक आप एक value assign न करें। - एक string enum को
status === "ACTIVE"जैसे एक plain string के बजायStatus.Activeसे compare करना। - एक numeric enum expect करने वाले function में कोई भी number pass करना और यह assume करना कि यह validated है।
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: