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);
}
}