鸿蒙 任意类型转字符串

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);
  }
}
相关推荐
程序员潘Sir3 小时前
鸿蒙应用开发从入门到实战(八):ArkTS自定义组件语法
harmonyos·鸿蒙
高心星20 小时前
鸿蒙5.0应用开发——V2装饰器@Provider和@Consumer的使用
harmonyos
ChinaDragon1 天前
HarmonyOS:ArkTS卡片页面刷新
harmonyos
HMSCore1 天前
通知语音播报功能,解锁全新体验
harmonyos
HarmonyOS_SDK1 天前
通知语音播报功能,解锁全新体验
harmonyos
高心星1 天前
鸿蒙5.0应用开发——V2装饰器@ObservedV2和@Trace的使用
harmonyos
城中的雾1 天前
HarmonyOS应用拉起系列(三):如何直接拉起腾讯/百度/高德地图进行导航
前端·javascript·harmonyos