TypeScript 枚举序列化/反序列化

55 阅读1分钟
class UserRole extends Enum<string> {
    static readonly ADMIN = new UserRole("admin", "Administrator");
    static readonly EDITOR = new UserRole("editor", "Content Editor");
    static readonly VIEWER = new UserRole("viewer", "Read-only User");
    
    private constructor(
        public readonly value: string`,`
        public readonly displayName: string
    ) {
        super();
    }
    
    // JSON序列化
    public toJSON() {
        return this.value;
    }
    
    // 从JSON反序列化
    public static fromJSON(value: string): UserRole {
        return UserRole.fromValue(value);
    }
}

// 序列化示例
const role = UserRole.ADMIN;
const json = JSON.stringify(role); // ""admin""

// 反序列化示例
const parsedRole = UserRole.fromJSON(JSON.parse(json));
console.log(parsedRole === UserRole.ADMIN); // true

适用场景

  • 需要将枚举与JSON相互转换
  • 需要处理API响应中的枚举值
  • 需要保持前后端枚举值的一致性