enum กำหนดชุดของค่าคงที่ที่มีชื่อ TypeScript มี numeric enums และ string enums
ts
{ , , , }
.;
[];
{
= ,
= ,
}
.;
enum กำหนดชุดของค่าคงที่ที่มีชื่อ TypeScript มี numeric enums และ string enums
{ , , , }
.;
[];
{
= ,
= ,
}
.;
ซึ่งแตกต่างจากประเภท TypeScript ส่วนใหญ่ (ที่หายไปในเวลาคอมไพล์) enum ทั่วไปจะส่งออก JavaScript object ไปยังบันเดิลของคุณ นั่นเป็นเหตุผลว่าทำไมหลายทีมจึงชอบ union ของ string literals บวก as const ซึ่งเป็นระดับประเภทล้วนๆ:
// 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 เดียว
แต่เนื่องจากพวกมันส่งออกโค้ดรันไทม์และมีลักษณะเฉพาะ (numeric enums ถูกตรวจสอบอย่างหลวม) TypeScript สมัยใหม่มักชอบ string-literal unions สำหรับกรณีง่ายๆ — พวกมันเบากว่าและเซอร์ไลไลส์ตามธรรมชาติ
ใช้ enums เมื่อคุณต้องการ namespacing หรือ reverse mapping