You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript枚举转JSON时如何返回枚举键而非整数值?

解决TypeScript枚举转JSON时输出字符串键的问题

当你使用数字枚举时,JSON.stringify会默认输出枚举对应的数值。要让productType输出枚举键的字符串,有以下几种实用方案:

1. 手动转换枚举值为键名

利用TypeScript数字枚举的双向映射特性(数值和键名互相映射),在序列化时手动替换字段值:

const product: Product = { id: 1, productType: ProductType.Digital };
const serialized = JSON.stringify({
  ...product,
  productType: ProductType[product.productType]
});
// 输出结果:{"id":1,"productType":"Digital"}

这种方法适合单次、零散的序列化场景,简单直接。

2. 给对象添加toJSON方法

如果Product类型需要频繁序列化,可以通过实现toJSON方法让序列化自动处理枚举转换。因为TypeScript接口不能定义方法,你可以用类来实现接口:

export class ProductImpl implements Product {
  id: number;
  productType: ProductType;

  constructor(id: number, productType: ProductType) {
    this.id = id;
    this.productType = productType;
  }

  // 自定义序列化逻辑
  toJSON() {
    return {
      id: this.id,
      productType: ProductType[this.productType]
    };
  }
}

// 使用示例
const product = new ProductImpl(2, ProductType.Retail);
JSON.stringify(product); // 输出{"id":2,"productType":"Retail"}

JSON.stringify会自动调用对象的toJSON方法,返回的结果会被用来序列化,适合需要重复使用的场景。

3. 改用字符串枚举

如果项目允许修改枚举定义,直接定义字符串枚举是最省心的方案,序列化时会直接输出字符串值:

export enum ProductType {
  Retail = "Retail",
  Digital = "Digital"
}

const product: Product = { id: 3, productType: ProductType.Retail };
JSON.stringify(product); // 输出{"id":3,"productType":"Retail"}

这种方法从根源上解决问题,不需要额外的转换逻辑,推荐在新项目或可以修改枚举的场景中使用。

内容的提问来源于stack exchange,提问作者Blankman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:07:07