打字稿有联合,所以枚举是多余的吗? [英] Typescript has unions, so are enums redundant?

查看:58
本文介绍了打字稿有联合,所以枚举是多余的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从TypeScript引入并集类型以来,我想知道是否有任何理由声明枚举类型。考虑下面的枚举类型声明:

Ever since TypeScript introduced unions types, I wonder if there is any reason to declare an enum type. Consider the following enum type declaration:

enum X { A, B, C }
var x:X = X.A;

和类似的联合体类型声明:

and a similar union type declaration:

type X: "A" | "B" | "C"
var x:X = "A";

如果它们基本上具有相同的目的,并且工会更强大且更具表现力,那么为什么枚举是必要的?

If they basically serve the same purpose, and unions are more powerful and expressive, then why are enums necessary?

推荐答案

据我所知,它们不是多余的,因为联合类型纯粹是编译时,概念,而枚举实际上已转译并最终出现在生成的javascript中(样本)。

As far as I see they are not redundant, due to the very simple reason that union types are purely a compile time concept whereas enums are actually transpiled and end up in the resulting javascript (sample).

这可以让您对枚举做一些事情,否则用联合类型是不可能的(例如枚举可能的枚举值

This allows you to do some things with enums, that are otherwise impossible with union types (like enumerating the possible enum values)

这篇关于打字稿有联合,所以枚举是多余的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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