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

TypeScript中如何遍历对象并转换字符串为对应数字或布尔值?

批量转换API响应字符串值为对应类型

你可以编写一个通用转换函数,遍历对象属性并根据值的内容自动转换类型,无需逐个处理每个属性。以下是TypeScript的实现方案:

实现思路

  • 遍历对象的每个键值对
  • 对每个字符串值做判断:
    • 若字符串是"true"或"false",转换为对应的布尔值
    • 若字符串可解析为有效数字(非NaN),转换为数字类型
    • 其他情况保留原字符串

代码实现

// 定义你的Person接口
interface Person {
  age: string | number;
  name: string;
  hasChildren: string | boolean;
  // 其他50+属性...
}

// 通用转换函数
function transformApiResponse<T extends Record<string, string>>(response: T): { [K in keyof T]: T[K] extends "true" | "false" ? boolean : T[K] extends `${number}` ? number : T[K] } {
  const result: any = {};
  for (const key in response) {
    if (Object.prototype.hasOwnProperty.call(response, key)) {
      const value = response[key];
      // 处理布尔值转换
      if (value === "true" || value === "false") {
        result[key] = value === "true";
      } 
      // 处理数字转换,排除空字符串误转0的情况
      else if (!isNaN(Number(value)) && value.trim() !== "") {
        result[key] = Number(value);
      } 
      // 保留原字符串
      else {
        result[key] = value;
      }
    }
  }
  return result;
}

// 使用示例
const responseFromApi: Record<string, string> = {
  age: "20",
  name: "John",
  hasChildren: "true"
  // 其他属性...
};

const afterTreatment = transformApiResponse(responseFromApi) as Person;
console.log(afterTreatment);
// 输出:{ age: 20, name: "John", hasChildren: true }

说明

  • 泛型T确保函数可处理任意结构的字符串对象,返回类型会自动推断转换后的类型
  • 使用as Person做类型断言,确保转换后的对象符合你的接口定义
  • 增加value.trim() !== ""判断,避免空字符串被误转为0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:36:34