在 TypeScript 里,要定義一個入參為any
類型、返回值為string
類型的函數,可參考下面幾種實現方式:
1. 基礎實現
直接把入參轉換為字符串返回。
function anyToString(input: any): string {return String(input); // 使用String()進行類型轉換
}// 示例
console.log(anyToString(123)); // "123"
console.log(anyToString(true)); // "true"
console.log(anyToString({ a: 1 })); // "[object Object]"
2. 自定義轉換邏輯
依據輸入值的類型,執行不同的轉換邏輯。
function anyToString(input: any): string {if (typeof input === "string") {return input; // 字符串直接返回} else if (typeof input === "object") {if (input === null) return "null";try {return JSON.stringify(input); // 對象轉JSON字符串} catch (e) {return String(input); // 轉換失敗則使用默認轉換}} else if (typeof input === "function") {return input.toString(); // 函數轉字符串} else {return String(input); // 其他類型使用默認轉換}
}// 示例
console.log(anyToString({ name: "Alice" })); // "{"name":"Alice"}"
console.log(anyToString(() => {})); // "function () {}"
3. 安全轉換(避免undefined
和null
)
為undefined
和null
提供默認值。
function anyToString(input: any): string {if (input === undefined) return ""; // 處理undefinedif (input === null) return ""; // 處理nullreturn String(input);
}// 示例
console.log(anyToString(undefined)); // ""
console.log(anyToString(null)); // ""
4. 類型守衛輔助
結合類型守衛,讓轉換邏輯更加清晰。
function isObject(input: any): input is object {return typeof input === "object" && input !== null;
}function anyToString(input: any): string {if (typeof input === "string") return input;if (isObject(input)) {try {return JSON.stringify(input);} catch {return "[object]";}}return String(input);
}
5. 處理特殊對象
針對特定類型的對象(如 Date),進行特殊處理。
function anyToString(input: any): string {if (input instanceof Date) {return input.toISOString(); // 日期轉ISO字符串}if (typeof input === "object" && input !== null) {return JSON.stringify(input);}return String(input);
}// 示例
console.log(anyToString(new Date())); // "2023-01-01T00:00:00.000Z"
注意事項
-
使用
String()
還是.toString()
?String(input)
能處理null
和undefined
(返回"null"
和"undefined"
)。input.toString()
在輸入為null
或undefined
時會報錯。
-
對象循環引用問題:
typescript
const obj = { a: 1 }; obj.self = obj; // 循環引用// console.log(anyToString(obj)); // 會觸發JSON.stringify()錯誤
總結
依據實際需求,挑選合適的轉換策略:
// 簡單版本
function anyToString(input: any): string {return String(input);
}// 增強版本
function anyToString(input: any): string {if (input === undefined || input === null) return "";if (input instanceof Date) return input.toISOString();if (typeof input === "object") {try {return JSON.stringify(input);} catch {return String(input);}}return String(input);
}