TS4.1 の Template Literal Types を使った Casing の変換。
多分n番煎じ。
環境: 4.1.1-rc
Snake to Camel
type Snake2Camel<T extends string> = T extends `${infer R1}_${infer R2}` ? `${R1}${Capitalize<Snake2Camel<R2>>}` : T;
const camel: Snake2Camel<"ho_gef_ugap_iyo"> = "hoGefUgapIyo";
Camel to Snake
type Capital = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z";
type Camel2Snake<T extends string> = T extends `${infer R1}${infer R2}` ? R1 extends Capital ? `_${Uncapitalize<R1>}${Camel2Snake<R2>}` : `${R1}${Camel2Snake<R2>}` : T;
const snake: Camel2Snake<"hoGefUgapIyo"> = "ho_gef_ugap_iyo";
まとめ
ts楽しい