Numeric Enums की जानकारी
In this page:
enum EnumName {
Member1 = 1,
Member2,
Member3,
}
Basic Numeric Enum
एक numeric enum जब कोई initializer न दिया जाए तो 0 से शुरू होने वाली increasing numeric values अपने आप assign करता है, इसलिए पहला member 0 है, दूसरा 1 है, और ऐसे ही आगे जब तक आप इसे override न करें।
उदाहरण: Basic Numeric Enum
enum Direction {
Up,
Down,
Left,
Right,
}
console.log(Direction.Up, Direction.Right);
Custom Numeric Values
Enum members एक चुने गए number से शुरू हो सकते हैं, और उसके बाद हर member वहां से increment होता रहता है — उपयोगी जब underlying numeric values को किसी external system की अपनी numbering से match करना हो।
उदाहरण: Custom Numeric Values
enum StatusCode {
Ok = 200,
NotFound = 404,
ServerError = 500,
}
console.log(StatusCode.NotFound);
Using Numeric Enums in Functions
Functions एक enum value को एक parameter type के रूप में accept कर सकते हैं callers को named numeric choices में से एक तक restrict करने के लिए, बजाय एक bare number accept करने के जो कोई भी arbitrary integer हो सकता है।
उदाहरण: Using Numeric Enums in Functions
enum Direction { Up, Down, Left, Right }
function move(direction: Direction) {
return `Moving in direction ${direction}`;
}
console.log(move(Direction.Left));
Numeric Enum Comparisons
Numeric enum values को named members के साथ directly compare किया जा सकता है जब business logic genuinely assigned specific number पर depend करती है, हालांकि यह code को उन exact values से couple कर देता है।
उदाहरण: Numeric Enum Comparisons
enum Priority { Low = 1, Medium, High }
const level = Priority.Medium;
console.log(level === Priority.Medium, level > Priority.Low);
When to Use Numeric Enums
Numeric enums सबसे अच्छे fit होते हैं जब named states को stable numeric values चाहिए, खासकर जब उन numbers का एक meaningful external representation हो — जैसे एक legacy system या database से status codes match करना।
उदाहरण: When to Use Numeric Enums
enum HttpStatus {
Ok = 200,
Created = 201,
NotFound = 404,
}
console.log(HttpStatus.Created);
- यह भूल जाना कि numeric enums
0से शुरू होते हैं, इसलिएDirection.Upfalsy है औरif (dir)इसे skip करता है। - यह मान लेना कि एक numeric enum सिर्फ अपने members accept करता है, जब older TypeScript versions कोई भी number accept करती हैं (5.0+ में enum members की unions के साथ)।
- Members को reorder करना या बीच में एक नया insert करना, जो बाकी के numbers को silently बदल देता है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: