鸿蒙 任意类型转字符串

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);
  }
}
相关推荐
不爱吃糖的程序媛35 分钟前
Flutter-OH OAuth 鸿蒙平台适配详细技术文档
javascript·flutter·harmonyos
讯方洋哥40 分钟前
判断、循环
harmonyos
未来之窗软件服务1 小时前
幽冥大陆(五十四)V10酒店门锁SDK 鸿蒙(HarmonyOS)——东方仙盟筑基期
华为·harmonyos·仙盟创梦ide·东方仙盟·东方仙盟sdk
柒儿吖1 小时前
命令行esh在开源鸿蒙PC平台的工程实践
开源·harmonyos·命令行
Lois_Luo2 小时前
基于鸿蒙(HarmonyOS)系统的 GPS 数据采集 APP 设计与实现方案
华为·harmonyos·gps采集
子榆.2 小时前
Flutter 与开源鸿蒙(OpenHarmony)离线能力与数据同步架构设计:打造高可用跨端应用
flutter·开源·harmonyos
不爱吃糖的程序媛3 小时前
开源鸿蒙跨平台赋能:Flutter/RN/KMP/CMP 多栈适配
flutter·开源·harmonyos
狮子也疯狂3 小时前
【鸿蒙小程序】| 鸿蒙系统中的元服务创新与实践
小程序·notepad++·harmonyos
萌虎不虎12 小时前
【在鸿蒙系统中实现拍照预览功能】
华为·harmonyos
萌虎不虎14 小时前
【鸿蒙实现显示屏测试实现方法】
华为·harmonyos