【问题标题】:what is the significant of enum in typescript打字稿中枚举的意义是什么
【发布时间】:2018-03-08 08:48:54
【问题描述】:

在打字稿中枚举的用途是什么。如果它的目的只是使代码可红色,我们不能只使用常量来实现相同的目的

enum Color {
Red = 1, Green = 2, Blue = 4
};


let obj1: Color = Color.Red;
obj1 = 100; // does not show any error in IDE while enum should accept some specific values

如果没有类型检查的优势,就不能直接写成。

const BasicColor = {
    Red: 1,
    Green: 2,
    Blue: 4
};

let obj2 = BasicColor.Red;

【问题讨论】:

标签: typescript


【解决方案1】:

首先,如下:

const BasicColor = {
    Red: 1,
    Green: 2,
    Blue: 4
};

RedGreenBlue 仍然是可变的(尽管它们不在枚举中)。


枚举还提供了一些东西:

  1. 一组封闭的众所周知的值(以后不允许出现拼写错误),每个都有...
  2. 为每个成员分别提供一组类似字面量的类型,所有这些类型均已提供...
  3. 通过包含所有值的单个命名类型

例如,要使用命名空间之类的东西,您必须执行类似的操作

export namespace Color
    export const Red = 1
    export type Red = typeof Red;

    export const Green = 2;
    export type Green = 2;

    export const Blue = 3;
    export type Blue = typeof Blue;
}
export type Color = Color.Red | Color.Blue | Color.Green

您还注意到一些不幸的遗留行为,其中 TypeScript 允许将任何数值分配给数字枚举。

但是,如果您使用的是字符串枚举,则不会出现这种行为。您还可以使用联合枚举启用其他功能,例如详尽检查:

enum E {
  Hello = "hello",
  Beautiful = "beautiful",
  World = "world"
}

// if a type has not been exhaustively tested,
// TypeScript will issue an error when passing
// that value into this function
function assertNever(x: never) {
  throw new Error("Unexpected value " + x);
}

declare var x: E;
switch (x) {
  case E.Hello:
  case E.Beautiful:
  case E.World:
    // do stuff...
    break;
  default: assertNever(x);
}

【讨论】:

  • 感谢您的撰写。您是否有“一些不幸的遗留行为,其中 TypeScript 允许将任何数值分配给数值枚举”的来源?
  • 我在an answer here 中解释了这种行为。 @DanielRosenwasser,将其描述为“不幸”是否意味着您可以接受 GitHub 中的建议,以允许对数字枚举的“严格/封闭”版本进行一些表示法?
  • @jcalz 也许,但老实说,我不认为想用标志或新结构使事情进一步复杂化。所以请随意这样做,但我认为我们对此有所保留。
猜你喜欢
  • 2018-06-12
  • 2020-04-30
  • 2020-01-29
  • 1970-01-01
  • 2017-03-06
  • 2017-05-09
  • 1970-01-01
  • 2017-06-08
  • 2020-10-27
相关资源
最近更新 更多