鸿蒙 任意类型转字符串

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);
  }
}
相关推荐
爱笑的眼睛119 小时前
深入浅出 HarmonyOS 应用开发:ArkTS 语法精要与实践
华为·harmonyos
爱笑的眼睛1110 小时前
HarmonyOS应用开发深度解析:ArkTS语法精要与UI组件实践
华为·harmonyos
Kisang.12 小时前
【HarmonyOS】消息通知
华为·harmonyos
安卓开发者14 小时前
鸿蒙NEXT网络通信实战:使用HTTP协议进行网络请求
网络·http·harmonyos
爱笑的眼睛1115 小时前
HarmonyOS ArkTS深度解析:构建高性能声明式UI应用
华为·harmonyos
TiZizzz17 小时前
HarmonyOS应用开发 - strip编译配置优先级
华为·harmonyos
徐归阳18 小时前
DevEco Studio安装
编辑器·harmonyos
小白学鸿蒙1 天前
OpenHarmony(开源鸿蒙)小白入门教程
harmonyos·鸿蒙·鸿蒙系统
安卓开发者2 天前
鸿蒙NEXT网络通信进阶:全方位优化HTTP传输性能
http·华为·harmonyos
爱笑的眼睛112 天前
HarmonyOS 应用开发深度解析:ArkTS 状态管理与渲染控制的艺术
华为·harmonyos