鸿蒙 任意类型转字符串

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);
  }
}
相关推荐
2401_8823515213 分钟前
开源鸿蒙平台 CMP 三方库「LlmTypewriter」适配全流程
华为·开源·harmonyos
2501_9481226310 小时前
开源鸿蒙平台 CMP 三方库「kmp-showcase-compose」适配全流程
华为·开源·harmonyos
OH_TPC10 小时前
HarmonyOS APP开发---“旅图“旅行摄影社区App,需要用到这个库
华为·harmonyos·鸿蒙
独隅13 小时前
HarmonyOS 系统能力与体验深度评测
华为·harmonyos·harmonyos 7.0
2601_9495758613 小时前
开源鸿蒙平台 CMP 三方库「Persian-Date-picker」适配全流程
华为·开源·harmonyos
KevinChaos14 小时前
灶台菜谱设计手记 02|HarmonyOS 7.0 空间化:菜图滚动实现
harmonyos
独隅15 小时前
HarmonyOS 全场景智能应用落地指南
华为·harmonyos·harmonyos 7.0
熊猫钓鱼>_>15 小时前
鸿蒙PC构建实战:hvigor modelVersion 降级 + schema 清理 + ArkTS 编译三连坑完整复盘
开发语言·华为·ai编程·harmonyos·openharmony·数据·ai生成
2601_9499706915 小时前
开源鸿蒙平台 CMP 三方库「SaltUI」适配全流程
华为·开源·harmonyos
马剑威(威哥爱编程)15 小时前
【HarmonyOS 7 小艺智能体实战】06:VibeCoding 十分钟搓出一个 Skill(上)——从想法到生成
人工智能·华为·harmonyos