node.js - nodejs中最接近枚举的实现是什么?
问题描述
许多语言都有枚举作为内置类型。
我需要知道使用以下语法在节点中最接近的枚举实现是什么:
enum Types{
TypeA,
TypeB,
TypeC,
}
我想像这样使用它。(我不想为每个变量赋值)
let x = Types.TypeA;
if(x == Types.TypeA){
console.log('A')
}
if(x == Types.TypeB){
console.log('B')
}
解决方案
您实际上可以将 Typescript 用于枚举 - 如果您想要提高性能,可以加分:使用 const enum :)
来自https://www.typescriptlang.org/docs/handbook/enums.html:
常量枚举只能使用常量枚举表达式,并且与常规枚举不同,它们在编译期间会被完全删除。常量枚举成员在使用站点内联。这是可能的,因为 const 枚举不能有计算成员。
const enum Direction {
Up,
Down,
Left,
Right,
}
let directions = [
Direction.Up,
Direction.Down,
Direction.Left,
Direction.Right,
];
in generated code will become
"use strict";
let directions = [
0 /* Up */,
1 /* Down */,
2 /* Left */,
3 /* Right */,
];
如果您不想使用 Typescript(尽管我强烈推荐它),恐怕您将不得不求助于一个对象:
const Types = {
"TypeA": 0,
"TypeB": 1,
"TypeC": 2,
}
推荐阅读
- angular - 找不到或无法读取要导入的文件:@material/button/mdc-button
- java - 在删除记录期间处理错误
- c# - .NET Framework 4.5 上的 Azure Function V2 HttpClient POST 到 WebAPI 导致 NULL 有效负载
- javascript - 在同构反应应用程序中的快速中间件之间传递状态
- javascript - 将缓冲区分成大小 rxjs
- windows - Puppet 无法在 C:\windows\system32 文件夹中创建文件
- ios - 视觉框架从捕获的视频输出中为帧中的矩形提供不正确的坐标
- excel-formula - EXCEL:如何编程限制计算
- javascript - 在给定的 React 组件中单击两个按钮有什么区别?
- typescript - 打字稿导入文本文件“错误 TS2307:找不到模块”