TS为什么不将符号用于枚举 [英] Why doesn't TS use Symbols for enums
问题描述
ES6符号非常适合枚举,因为它们避免了冲突。我想如果 target:'es6'
,TS enum
类型将符号用于枚举,但是没有:
ES6 symbols is a great fit for enums as they avoid collision. I thouhgt that TS enum
type used Symbols for enums if target:'es6'
, but it doesn't:
enum Role {Employee, Manager, Admin}
let role: Role = Role.Employee;
transpiles到
transpiles to
var Role;
(function (Role) {
Role[Role["Employee"] = 0] = "Employee";
Role[Role["Manager"] = 1] = "Manager";
Role[Role["Admin"] = 2] = "Admin";
})(Role || (Role = {}));
let role = Role.Employee;
有什么想法吗?通过这种方法, Role.Employee
的值为 0
,而任何其他枚举的值为<$ c $是否可以在运行时使用c> 0 代替 Role.Employee
?
any ideas why? With such approach Role.Employee
has the value of 0
, and any other enum with the value of 0
can be used instead of Role.Employee
in runtime?
推荐答案
ES 符号
与唯一性有关,而TypeScript enum
与命名常量有关。 唯一和恒定是两件事。
ES Symbol
is about uniqueness whereas TypeScript enum
is about named constants. Being unique and being constant are two different things.
我们可以序列化 enum
结构,因为它实际上只是一个对象。但是 Symbol
是另一回事。您不能序列化它。
We can serialize enum
structure as it is essentially just an object. But Symbol
is a different story. You cannot serialize it.
因此,当我们说常量时,实际上是指使用该值,因为它恰好是枚举 C $ C>提供。但是
Symbol
不是您要使用的值。
So, when we say constant, we actually mean to use that value as it is which exactly what enum
provides. But Symbol
is not a value that you want to use. It is more like an identity that we wish to make that nobody should be able to clone/replicate.
常量是保持不变的东西。这更像是我们希望使任何人都不能克隆/复制的标识。
A constant is something that stays constant. So some code that can run in two different environments, like Node.js and Browser, both will understand the constant value to be same (in simple words, the developer is creating a value for constant, ex. string or number). But for Symbol
, imagine it to not have any notion of value. If we attempt to use it as value, then it means it is two separate things (because the runtime is creating those Symbol
values, not developer).
同样,如果您使用过redux,则相对于符号
string >来表示我们的动作。
In the same light, if you have used redux, we prefer string
over Symbol
to represent our action.
此外, ,枚举
也可以用作环境
或替代
值。在这种情况下,它是枚举值重要的唯一编译器。在编译期间,类型擦除
可能会完全删除枚举
引用。现在,这是你不能做的符号。 符号
的创建是仅运行时活动。因此,如果我们为枚举
使用 Symbol
,那么我们就失去了枚举的能力 code>来为的编译时只强>特征。
Further, in case of TypeScript, enum
can also be used as ambient
or substitution
value. In this case, it is the only compiler for whom the enum value matters. During compilation, type erasure
may remove enum
reference altogether. Now, this is something you cannot do with Symbol. Creation of Symbol
is runtime only activity. So if we use Symbol
for enum
, then we lose to the ability of enum
to be compile-time only feature.
因此不使用符号
对于枚举
似乎是明智的选择。
Thus not using Symbol
for enum
seems a sensible choice.
这篇关于TS为什么不将符号用于枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!