鸿蒙 任意类型转字符串

FormatType.ets 复制代码
export type AllType = string | number | boolean | object | null | undefined;

/**
 * 格式化选项接口
 */
export interface FormatOptions {
  prefix?: string;
}

/**
 * 格式化类型
 * console.log(formatType("hello")); // "hello"
 * console.log(formatType([1, 2, 3], { prefix: "Debug: " })); // "Debug: [1,2,3]"
 * console.log(formatType({ a: 1 })); // " {"a":1}"(自动使用空前缀)
 */
export function formatType(
  type: AllType,
  options?: FormatOptions // 使用接口替代对象字面量
): string {
  // 手动设置默认值
  const prefix = options?.prefix || "";

  switch (typeof type) {
    case "string":
      return type;
    case "number":
    case "boolean":
      return String(type);
    case "object":
      if (type === null) {
        return "null";
      }
      if (Array.isArray(type)) {
        try {
          return `${prefix} ${JSON.stringify(type)}`;
        } catch {
          return `${prefix} []`;
        }
      }
      try {
        return `${prefix} ${JSON.stringify(type)}`;
      } catch {
        return `${prefix} {}`;
      }
    case "undefined":
      return "undefined";
    default:
      return String(type);
  }
}
相关推荐
FF2501_940228589 小时前
HarmonyOS应用开发实战:猫猫大作战-在排行榜和历史记录查询中,排序是必不可少的操作【apple_product_name】
华为·harmonyos·鸿蒙
程序员黑豆13 小时前
鸿蒙应用开发:@Provider 与 @Consumer 跨组件双向同步详解
前端·harmonyos
程序员黑豆14 小时前
鸿蒙应用开发之跨组件传参:@Provide 与 @Consume 跨层级数据同步详解
前端·harmonyos
懿路向前14 小时前
【HarmonyOS学习笔记】2026-07-30 | 小艺开放平台智能体接入实战
笔记·学习·harmonyos
大锅盖114 小时前
HarmonyOS ArkTS 的新手练手样例:从 Text 和 Button 开始,做一个会变化的计数页面
华为·harmonyos
袁震16 小时前
小图传输,大图呈现——用 HarmonyOS 7 端侧 AI 实现 4 倍图像超分重建
人工智能·华为·harmonyos
结网的兔子17 小时前
【前端开发】Web端迁移至 uni-app 及鸿蒙扩展方案对比
前端·uni-app·harmonyos
落叶飘飘s17 小时前
餐饮服务与软件创新的融合:解析海底捞 APP 的 Flutter 鸿蒙开发之路
flutter·华为·harmonyos
qizayaoshuap19 小时前
# HarmonyOS ArkTS 滑动删除列表实战(三):交互式列表增删操作
华为·harmonyos
GitCode官方20 小时前
openPangu-2.0-Pro 模型及技术报告正式开源上线 AtomGit AI
人工智能·华为·开源·harmonyos·atomgit