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

如何通过TypeScript泛型将对象中特定类型转换为字符串?

实现方案

完全可以通过TypeScript的类型操作实现这个需求,核心思路是利用映射类型结合条件类型,编写通用泛型自动转换目标类型。

基础版本(扁平对象)

针对扁平结构的对象,先实现基础泛型:

// 定义通用转换泛型
type JsonSerialized<T> = {
  [K in keyof T]: T[K] extends Decimal | Date ? string : T[K];
};

// 你的源类型
type Source = {
  id: string
  name: string
  price: Decimal
  createdAt: Date
};

// 自动生成目标类型
type Destination = JsonSerialized<Source>;

这个泛型逻辑直白:遍历源类型T的所有键K,若该键对应类型是Decimal或Date,则替换为string;其他类型保持原样。最终Destination的类型完全符合预期。

进阶版本(支持嵌套对象)

如果源类型包含嵌套对象,需要递归处理内部的Decimal和Date类型,调整泛型为递归版本:

type JsonSerialized<T> = 
  // 先判断当前类型是否为Decimal或Date,直接转string
  T extends Decimal | Date 
    ? string 
    // 如果是对象类型,递归处理每个属性
    : T extends object 
      ? { [K in keyof T]: JsonSerialized<T[K]> } 
      // 非对象非目标类型,保持原类型
      : T;

示例嵌套结构的源类型:

type NestedSource = {
  id: string
  orderInfo: {
    totalPrice: Decimal
    createTime: Date
    items: { name: string; price: Decimal }[]
  }
};

type NestedDestination = JsonSerialized<NestedSource>;

生成的NestedDestination中,所有层级的Decimal和Date都会被转换为string,其他类型不受影响。

注意事项

  • 这里的Decimal需要和你项目中实际使用的类型名称一致(比如使用decimal.js库的Decimal类型时直接引用即可)。
  • 该泛型完全匹配JSON.stringify+JSON.parse后的实际类型——这两个操作确实会把Date转为ISO字符串,自定义Decimal类会被序列化为其字符串表示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:15:26