TS为什么不将符号用于枚举 [英] Why doesn't TS use Symbols for enums

查看:160
本文介绍了TS为什么不将符号用于枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆