你可能不需要 TypeScript Enum

2025-06-07

你可能不需要 TypeScript Enum

TypeScript 中有一个功能叫做枚举,Enum它不是 JavaScript 的类型级扩展。枚举允许开发人员定义一组命名常量。

enum EDirection {
  Up = "Up",
  Down = "Down",
  Left = "Left",
  Right = "Right",
}

// Using the enum as a parameter
function walk(dir: EDirection) {}

walk(EDirection.Left);
Enter fullscreen mode Exit fullscreen mode

但是,另一方面,我们可能不需要 Enum,正如 TypeScript 团队在https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums上所说,通过使用带有的对象as const

const ODirection = {
  Up: "Up",
  Down: "Down",
  Left: "Left",
  Right: "Right",
} as const;


type Direction = typeof ODirection[keyof typeof ODirection];

function run(dir: Direction) {}

run(ODirection.Right);
Enter fullscreen mode Exit fullscreen mode

那么枚举和对象之间有什么区别呢?我将讨论数据类型、Bundle 大小以及如何使用方面的区别。

数据类型

枚举

TypeScript 提供数字和基于字符串的枚举。

// Numeric Enums
enum UserResponse {
  No = 0,
  Yes = 1,
}

// String Enums
enum UserResponse {
  No = "No",
  Yes = "Yes",
}
Enter fullscreen mode Exit fullscreen mode

常量

Constants可以覆盖具有字符串和数字属性值的对象,包括所有数据类型。

// Number
const PI = 3.14159;

// String
const GREETING = "Hello, World!";

// Boolean
const IS_ACTIVE = true;

// Array
const COLORS = ["red", "green", "blue"];

// Object
const PERSON = {
    name: "John",
    age: 30
};

// RegExp
const EMAIL_PATTERN = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

// Null
const NO_VALUE = null;

// Undefined
const UNDEFINED_VALUE = undefined;

// Symbol
const UNIQUE_KEY = Symbol("unique");
Enter fullscreen mode Exit fullscreen mode

转译大小

我使用https://babeljs.io/repl来了解代码转换后的大小。

枚举

enum Color {
    Red = "RED",
    Green = "GREEN",
    Blue = "BLUE"
}

// Transpiled Result
var Color = /*#__PURE__*/function (Color) {
  Color["Red"] = "RED";
  Color["Green"] = "GREEN";
  Color["Blue"] = "BLUE";
  return Color;
}(Color || {});

// Size: 153 Bytes
Enter fullscreen mode Exit fullscreen mode

常量

const COLOR = {
    red: "RED",
    green: "GREEN",
    blue: "BLUE"
} as const;

// Transpiled Result
const COLOR = {
  red: "RED",
  green: "GREEN",
  blue: "BLUE"
};

// Size: 65 Bytes
Enter fullscreen mode Exit fullscreen mode

如何使用

枚举名EDirection和对象名指的ODirection是我们之前讨论过的同一件事。

枚举

walk("Left");
// This shows an error ❌
// (Argument of type '"Left"' is not assignable to parameter of type 'EDirection')

walk(EDirection.Left);
// This works well ✅
Enter fullscreen mode Exit fullscreen mode

持续的

run("Left");
// This works well ✅

run(ODirection.Left);
// This works well ✅
Enter fullscreen mode Exit fullscreen mode

结论

基于我之前讨论过的几个方面,我们可以用 Object 替换 Enum。Object 可以灵活地定义各种数据类型,转换后的大小更小,并且可以同时检测属性值或属性访问。

所以,务必记住,并非所有炫酷的功能都是最佳选择。务必评估你认为重要的方面。如果某个功能没有任何负面影响,那么你就可以放心使用它。

文章来源:https://dev.to/maafaishal/you-might-not-need-typescript-enum-1f4n
PREV
4 个很棒的原型设计 Web 工具。1. Placeholder.com 2. iHateRegex 3. {JSON} Placeholder 4. ngrok
NEXT
您需要了解的软件要求