what is the significant of enum in typescript

匿名 (未验证) 提交于 2019-12-03 01:08:02

问题:

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 

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; 

回答1:

First, in the following:

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

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


Enums also provide a few things:

  1. a closed set of well known values (that won't permit typos later on), each which has...
  2. a respective set of literal-like types for each member, all which are provided...
  3. by a single named type which encompasses all values

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 

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!