鸿蒙 任意类型转字符串

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);
  }
}
相关推荐
Goway_Hui1 小时前
【ReactNative鸿蒙化-三方库使用与C-API集成】
c语言·react native·harmonyos
nashane2 小时前
HarmonyOS 6.0 分布式相机实战:调用远端设备摄像头与AI场景识别(API 11+)
分布式·数码相机·harmonyos·harmonyos 5
Huanzhi_Lin2 小时前
鸿蒙NEXT出包
华为·harmonyos·鸿蒙·harmony·鸿蒙next·hap
╰つ栺尖篴夢ゞ3 小时前
HarmonyOS Next面试题之主线程与子线程访问同一个单例,获取的对象是同一个吗?
单例模式·多线程·harmonyos·sendable·actor模型·内存隔离
南村群童欺我老无力.5 小时前
鸿蒙PC开发的@Builder函数闭合大括号的隐形杀手
华为·harmonyos
花先锋队长5 小时前
从静态到“AI动态”:华为Pura X Max独家首发AI动态漫画再创阅读新体验
科技·华为·harmonyos
Lanren的编程日记5 小时前
Flutter 鸿蒙应用错误处理优化实战:完善全局异常捕获,全方位提升应用稳定性
flutter·华为·harmonyos
Lanren的编程日记6 小时前
Flutter鸿蒙应用开发:网络请求优化实战,全方位提升请求稳定性与性能
网络·flutter·harmonyos
IntMainJhy6 小时前
【futter for open harmony】Flutter 鸿蒙聊天应用实战:shared_preferences 本地键值存储适配指南[特殊字符]
flutter·华为·harmonyos
IntMainJhy6 小时前
【Flutter for OpenHarmony 】第三方库鸿蒙电商实战|首页模块完整实现[特殊字符]
flutter·华为·harmonyos