步骤2:使用 Enum 中的 Key 来获取值 接下来,我们将学习如何根据 Enum 中的键来获取相应的值。我们可以直接通过 Enum 的名称和键来实现这一操作。以下是具体的代码示例: // 根据 Enum 中的 key 获取值constredValue=Color.Red;// 通过 Color.Red 获取对应的值// 打印获取到的值console.log(redValue);// ...
// 假设我一个枚举enumENUM_TYPE{ALL='all',SOME='some',LITTLE='little'}// 获取枚举的 valuetypeIValue=`${ENUM_TYPE}`// 'all' | 'some' | 'little'// 获取枚举的 keytypeIKey=keyoftypeofENUM_TYPE// 'ALL' | 'SOME' | 'LITTLE'
在 TypeScript 中,我们可以使用对象字面量来定义映射对象。 constkeyMap:{[keyinKeyEnum]:string}={[KeyEnum.Key1]:"value1",[KeyEnum.Key2]:"value2",[KeyEnum.Key3]:"value3",}; 1. 2. 3. 4. 5. 在上面的代码中,我们定义了一个映射对象keyMap,它使用枚举KeyEnum中的成员作为键,并将其关联到相...
它在保持与原生 enum 完全兼容的同时,提供了一系列增强功能。 enum-plus是一个 TypeScript 库,旨在提供更强大、更灵活的枚举解决方案。它通过简单的 API 设计,解决了原生 enum 的痛点,并提供了更多实用功能。 enum-plus允许你在定义枚举时直接添加显示文本、国际化支持、自定义属性等,极大地简化了枚举的使用和维护...
我们可以通过 Enum[key] 或者 Enum.key 的方式获取到对应的值。typescript 还支持反向映射,即可以通过值来获取键,不过反向映射只支持数字枚举。下面是个例子: enumStatus { Success=200, NotFound=404, Error=500} console.log(Status.Success)//200console.log(Status[200])//Successconsole.log(Status[Status....
数字enum 最大的“彩蛋”就是自动反向映射:键和值都能“变身”,debug 一不小心掉进无底洞。 constDirectionNumberKeys=Object.keys(DirectionNumber).filter((key)=>isNaN(Number(key)))as(keyoftypeofDirectionNumber)[];// [ 'Up', 'Down', 'Left', 'Right' ]constDirectionStringKeys=Object.keys(Direction...
这是一个类型安全的解决方案,而不是简单地调用let value = obj[key];之类的东西。 从这里getProperty函数很容易调用,如下面的例子所示,从typescript_info对象中获取属性: // the property we will get will be of type Difficultyenum Difficulty { Easy, Intermediate, Hard}// defining the object we will ...
* @enum {number} */constStatus={on:1,off:0,}; 定义类: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 classComputer{/** * @readonly Readonly property * @type {string} */CPU;/** * @private Private property */_clock=3.999;/** ...
enum类型是对JavaScript标准数据类型的一个补充。 像C#等其它语言一样,使用枚举类型可以为一组数值赋予友好的名字。 代码语言:javascript 代码运行次数:0 运行 AI代码解释 // 默认情况从0开始为元素编号,也可手动为1开始enumColor{Red=1,Green=2,Blue=4}letc:Color=Color.Green;letcolorName:string=Color[2];co...
export interface Interface {/*** Shortest name: {@link InterfaceL1.(:STRING_INDEXER)}* Full name: {@link (InterfaceL1:interface).(:STRING_INDEXER)}** {@label STRING_INDEXER}*/[key: string]: number;/*** Shortest name: {@link InterfaceL1.(:NUMBER_INDEXER)}* Full name: {@link (Inter...