鸿蒙 任意类型转字符串

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);
  }
}
相关推荐
Ww.xh44 分钟前
鸿蒙WebView IPC防伪造请求方案
华为·harmonyos
大雷神2 小时前
第25篇|Surface 预览控制:ArkUI 页面如何接住相机画面
harmonyos
大雷神3 小时前
第24篇|相机权限和设备枚举:先判断能力再打开预览
harmonyos
Goway_Hui3 小时前
【鸿蒙原生应用开发--ArkUI--003】TodoApp - 待办事项应用教程
华为·harmonyos
想你依然心痛3 小时前
HarmonyOS 6(API 23)智能体驱动的沉浸式AR航天器装配工坊
华为·ar·harmonyos·智能体
不羁的木木3 小时前
HarmonyOS文件基础服务(Core File Kit)实战演练05-实战:文件管理工具开发
华为·harmonyos
Goway_Hui3 小时前
【鸿蒙原生应用开发--ArkUI--007】TimerApp - 计时器应用教程
华为·harmonyos
nashane3 小时前
HarmonyOS 6学习:保存图片预览空白?沙箱路径转URI的“视觉修复”术
学习·华为·harmonyos
芒鸽3 小时前
HarmonyOS ArkTS 状态管理深度解析:@State、@Prop、@Link、@Provide/@Consume 实战指南
华为·harmonyos·arkts·状态管理
大雷神4 小时前
HarmonyOS APP<玩转React>开源教程三十一:示例项目下载功能
react.js·开源·harmonyos