TypeScript 範例
在 TypeScript 將 snake_case 轉為 camelCase
typed helper 可處理 underscore token,並回傳可預測的 camelCase 字串。
TypeScript 程式碼
function snakeToCamel(value: string): string {
const parts = value.trim().replace(/^_+|_+$/g, "").split(/_+/).filter(Boolean)
if (parts.length === 0) return ""
return parts[0].toLowerCase() + parts.slice(1).map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join("")
}
snakeToCamel("user_profile_image")
// "userProfileImage"string→string 形式容易在 typed utility、adapter 與 mapping code 中重用。
type-level remapping 與 runtime 資料轉換是不同層;網路資料仍必須實際在 runtime 轉換。
需要考慮的邊界案例
- 縮寫規則可能要求 apiResponseURL 而不是 apiResponseUrl。
- 遞迴轉換 object key 時,需要決定 TypeScript type 要反映 runtime 結果到什麼程度。
- 混合分隔符需要更通用的 tokenization。
- 不同來源鍵可能產生相同目標鍵,不能靜默覆寫。
範例
| 轉換前 | 轉換後 |
|---|---|
| user_profile_image | userProfileImage |
| __user__profile__ | userProfile |
| api_response_url | apiResponseUrl |
| created_at | createdAt |
TypeScript 程式碼
const cases: Array<[string, string]> = [
["user_profile_image", "userProfileImage"],
["__user__profile__", "userProfile"],
["api_response_url", "apiResponseUrl"],
["created_at", "createdAt"],
]
for (const [input, expected] of cases) {
if (snakeToCamel(input) !== expected) throw new Error(input)
}線上測試轉換
使用瀏覽器工具快速檢查、批次處理、縮寫或混合命名格式。
偵測:snake_case
camelCase 輸出
userProfileImageUrl
所有命名格式
camelCase
userProfileImageUrlPascalCase
UserProfileImageUrlsnake_case
user_profile_image_urlkebab-case
user-profile-image-urlCONSTANT_CASE
USER_PROFILE_IMAGE_URLdot.case
user.profile.image.urlpath/case
user/profile/image/url轉換會在瀏覽器本機執行,輸入不會傳送到轉換伺服器。