打字稿中枚举的意义是什么 [英] what is the significant of enum in typescript

查看:26
本文介绍了打字稿中枚举的意义是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打字稿中枚举的用途是什么.如果它的目的只是为了使代码可红,我们就不能为了同样的目的使用常量

what is use of enum in typescript. If it's purpose is only to make code redable can't we just use constant for same purpose

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

如果没有typechecking的优势,难道就不能这么写吗

If there is no advantage of typechecking, Can't it be just written as.

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

let obj2 = BasicColor.Red;

推荐答案

首先在下面:

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

RedGreenBlue 仍然是可变的(而它们不在枚举中).

Red, Green, and Blue are still mutable (whereas they are not in an enum).

枚举还提供了一些东西:

Enums also provide a few things:

  1. 一组封闭的众所周知的值(以后不允许输入错误),每个值都有...
  2. 为每个成员提供一组各自的类似文字的类型,所有这些都提供...
  3. 通过包含所有值的单个命名类型

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

To get that with something like a namespace, for example, you have to do something like

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 允许从任何数值赋值给数字枚举.


What you're also noting is some unfortunate legacy behavior where TypeScript permits assignment from any numeric value to a numeric enum.

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

But if you're using a string enum, you won't get that behavior. There are also other things like exhaustiveness checking that you can enable with union enums:

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);
}

这篇关于打字稿中枚举的意义是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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