你可能不需要 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);
但是,另一方面,我们可能不需要 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);
那么枚举和对象之间有什么区别呢?我将讨论数据类型、Bundle 大小以及如何使用方面的区别。
数据类型
枚举
TypeScript 提供数字和基于字符串的枚举。
// Numeric Enums
enum UserResponse {
No = 0,
Yes = 1,
}
// String Enums
enum UserResponse {
No = "No",
Yes = "Yes",
}
常量
而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");
转译大小
我使用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
常量
const COLOR = {
red: "RED",
green: "GREEN",
blue: "BLUE"
} as const;
// Transpiled Result
const COLOR = {
red: "RED",
green: "GREEN",
blue: "BLUE"
};
// Size: 65 Bytes
如何使用
枚举名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 ✅
持续的
run("Left");
// This works well ✅
run(ODirection.Left);
// This works well ✅
结论
基于我之前讨论过的几个方面,我们可以用 Object 替换 Enum。Object 可以灵活地定义各种数据类型,转换后的大小更小,并且可以同时检测属性值或属性访问。
所以,务必记住,并非所有炫酷的功能都是最佳选择。务必评估你认为重要的方面。如果某个功能没有任何负面影响,那么你就可以放心使用它。
文章来源:https://dev.to/maafaishal/you-might-not-need-typescript-enum-1f4n