DEV Community

Discussion on: How to UPPER_CASE to camelCase in raw Typescript generics

Collapse
 
silence_64 profile image
leere • Edited

Just two generics can do this

type SnakeToCamelCase<S extends string> =
  S extends `${infer T}_${infer U}` ?
  `${Lowercase<T>}${Capitalize<SnakeToCamelCase<U>>}` :
  S

type SnakeToCamelCaseNested<T> = T extends object ? {
  [K in keyof T as SnakeToCamelCase<K & string>]: SnakeToCamelCaseNested<T[K]>
} : T

Enter fullscreen mode Exit fullscreen mode
Collapse
 
svehla profile image
Jakub Švehla • Edited

In the time of writing this article lowercase and capitalise genericks did not exist.

I keep the article without changes because I wanted to demonstrate how to transform strings with low level features like rekursive iterations etc...


Iteration over keys with as keyword looks pretty handy! I have to chekt it! 😈

It's very nice generic! Thanks for sharing it !!!