TypeScript Enum 最佳实践:统一封装枚举取值与标签转换方法
统一维护枚举相关工具方法的实现方案
当然可以把这两个功能统一定义在枚举所在的QuestionType.ts文件中,这是符合代码复用、便于统一维护的最佳实践,和你熟悉的Java中给枚举配套工具逻辑的思路完全一致。
1. 改造QuestionType.ts文件
在枚举定义的同文件中,添加标签映射和静态工具方法(利用TypeScript的命名空间扩展枚举):
数字枚举场景(带反向映射)
// QuestionType.ts // 定义基础枚举 export enum QuestionType { SingleChoice = 1, MultipleChoice = 2, ShortAnswer = 3 } // 枚举值与标签的映射表 const typeLabelMap: Record<QuestionType, string> = { [QuestionType.SingleChoice]: "单选题", [QuestionType.MultipleChoice]: "多选题", [QuestionType.ShortAnswer]: "简答题" }; // 扩展枚举的静态方法 export namespace QuestionType { /** * 获取所有枚举数值 */ export function getAllValues(): QuestionType[] { // 数字枚举会生成反向映射,需过滤掉字符串类型的key return Object.values(QuestionType).filter(val => typeof val === "number") as QuestionType[]; } /** * 根据枚举值获取对应的标签 */ export function getLabel(type: QuestionType): string { return typeLabelMap[type] || "未知题型"; } }
字符串枚举场景(无反向映射)
如果是字符串枚举,可以简化getAllValues方法:
// QuestionType.ts export enum QuestionType { SingleChoice = "SINGLE_CHOICE", MultipleChoice = "MULTIPLE_CHOICE", ShortAnswer = "SHORT_ANSWER" } const typeLabelMap: Record<QuestionType, string> = { [QuestionType.SingleChoice]: "单选题", [QuestionType.MultipleChoice]: "多选题", [QuestionType.ShortAnswer]: "简答题" }; export namespace QuestionType { export function getAllValues(): QuestionType[] { return Object.values(QuestionType) as QuestionType[]; } export function getLabel(type: QuestionType): string { return typeLabelMap[type] || "未知题型"; } }
2. 在组件中复用方法
表单组件(填充下拉框)
import { Component } from '@angular/core'; import { QuestionType } from './QuestionType'; @Component({ selector: 'app-form', template: ` <select [(ngModel)]="selectedType"> <option *ngFor="let type of questionTypes" [value]="type"> {{ QuestionType.getLabel(type) }} </option> </select> ` }) export class FormComponent { // 暴露枚举给模板访问 QuestionType = QuestionType; selectedType: QuestionType; // 获取所有枚举值用于下拉框遍历 questionTypes = QuestionType.getAllValues(); }
列表组件(显示枚举标签)
import { Component } from '@angular/core'; import { QuestionType } from './QuestionType'; @Component({ selector: 'app-list', template: ` <ul> <li *ngFor="let item of questionList"> 题型:{{ QuestionType.getLabel(item.type) }} </li> </ul> ` }) export class ListComponent { // 暴露枚举给模板访问 QuestionType = QuestionType; questionList = [ { type: QuestionType.SingleChoice, content: "示例单选题" }, { type: QuestionType.ShortAnswer, content: "示例简答题" } ]; }
优势说明
- 所有与枚举相关的逻辑集中在一处,修改枚举值或标签时只需改动
QuestionType.ts,无需逐个修改组件 - 避免了组件间重复编写过滤、标签转换代码,减少冗余
- 符合TypeScript的类型安全特性,所有方法都基于枚举类型,避免传入非法值
内容的提问来源于stack exchange,提问作者AlphaTry
相关产品推荐
相关产品推荐

