鸿蒙 任意类型转字符串

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);
  }
}
相关推荐
BlackWolfSky1 小时前
鸿蒙三方库httpclient使用
华为·harmonyos·鸿蒙
爱笑的眼睛112 小时前
HarmonyOS 分布式输入法开发指南:实现跨设备无缝输入体验
华为·harmonyos
夏文强2 小时前
HarmonyOS开发-系统AI视觉能力-图片识别
人工智能·华为·harmonyos
Random_index2 小时前
#HarmonyOS篇:管理组件拥有的状态
华为·harmonyos
光芒Shine3 小时前
【HarmonyOS-App发布】
harmonyos
爱笑的眼睛1114 小时前
HarmonyOS分布式Kit深度解析:实现高效跨设备协同
华为·harmonyos
坚果的博客18 小时前
鸿蒙PC使用aarch64的原因分析
华为·harmonyos
HarmonyOS_SDK19 小时前
【FAQ】HarmonyOS SDK 闭源开放能力 — Push Kit
harmonyos
猫林老师20 小时前
Flutter for HarmonyOS开发指南(二):混合开发架构与通信机制
flutter·架构·harmonyos
特立独行的猫a1 天前
HarmonyOS黑马云音乐项目增加网络听歌功能(一、轮播图的实现)
网络·华为·harmonyos·开源项目·黑马云音乐