LoginSignup
1
0

More than 3 years have passed since last update.

Template Literal Types で Casing の変換をしてみた

Last updated at Posted at 2020-11-08

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楽しい

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0