Enum बनाम Union Types
In this page:
enum EnumName { A = "a", B = "b" }
type UnionName = "a" | "b";
Enum and Union Basics
Enums और union types दोनों एक value को known options के एक set तक restrict कर सकते हैं, लेकिन एक बार आप type-checking stage से आगे actual runtime behavior में जाएं तो वे fundamentally अलग तरीके से काम करते हैं।
उदाहरण: Enum and Union Basics
enum StatusEnum { Pending, Done }
type StatusUnion = "pending" | "done";
const a: StatusEnum = StatusEnum.Pending;
const b: StatusUnion = "pending";
console.log(a, b);
Runtime Differences
एक normal enum runtime पर एक real JavaScript object emit करता है जिसे आप inspect या log कर सकते हैं, जबकि एक union type पूरी तरह एक compile-time construct है जो TypeScript के JavaScript में compile होने के बाद पूरी तरह गायब हो जाता है।
उदाहरण: Runtime Differences
enum StatusEnum { Pending, Done }
console.log(StatusEnum); // a real object exists at runtime
type StatusUnion = "pending" | "done";
const b: StatusUnion = "pending"; // no runtime trace of the type itself
console.log(b);
Function Parameters
दोनों approaches type-checking level पर function arguments को known values के एक set तक equally अच्छी तरह restrict करते हैं — difference सिर्फ तब दिखता है जब code actually run होता है, कि क्या, अगर कुछ भी, exist करता है।
उदाहरण: Function Parameters
enum StatusEnum { Pending, Done }
type StatusUnion = "pending" | "done";
function handleEnum(s: StatusEnum) { return s; }
function handleUnion(s: StatusUnion) { return s; }
console.log(handleEnum(StatusEnum.Done), handleUnion("done"));
When Unions Are Simpler
एक literal union (जैसे "pending" | "done" | "failed") string values के एक छोटे, fixed set के लिए अक्सर simpler choice होता है जब आपको कोई runtime object या कोई enum-specific behavior जैसे reverse mapping नहीं चाहिए।
उदाहरण: When Unions Are Simpler
type Status = "pending" | "done" | "failed";
function label(status: Status) {
return `Status: ${status}`;
}
console.log(label("pending"));
When Enums Are Useful
Enums तब अपनी जगह कमाते हैं जब आपको एक shared runtime object से backed named members चाहिए, या जब numeric values genuinely इस बात पर मायने रखें कि application कैसे behave करे — ऐसी situations जो सिर्फ एक union type अकेले provide नहीं कर सकता।
उदाहरण: When Enums Are Useful
enum HttpStatus {
Ok = 200,
NotFound = 404,
}
function isSuccess(status: HttpStatus) {
return status === HttpStatus.Ok;
}
console.log(isSuccess(HttpStatus.Ok));
- यह उम्मीद करना कि एक union type runtime पर exist करता है, जब यह erased हो जाता है और iterate नहीं किया जा सकता।
- एक string enum type को एक plain string जैसे
"pending"assign करना, जो allowed नहीं है। - एक enum चुनना जब एक simple union काम कर जाता, बिना किसी फ़ायदे के extra JavaScript output जोड़ते हुए।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: