Skip to content

Instantly share code, notes, and snippets.

@kdmadej
Created February 12, 2021 15:22
Show Gist options
  • Select an option

  • Save kdmadej/c3e016bcc17f7803abe32d3923ed84f1 to your computer and use it in GitHub Desktop.

Select an option

Save kdmadej/c3e016bcc17f7803abe32d3923ed84f1 to your computer and use it in GitHub Desktop.
TypeScript template string literal type casing
type DefaultSeparator = '_' | '-';
type CamelCase<S extends string, Separator extends string = DefaultSeparator, Beginning extends boolean = true>
= S extends `${infer Character}${infer Rest}`
? Character extends Separator
? `${CamelCase<Capitalize<Rest>, Separator, Beginning>}`
: `${Beginning extends true ? Lowercase<Character> : Character}${CamelCase<Rest, Separator, false>}`
: '';
// Example: type T = "awaBbbCcc"
type T =
| CamelCase<'Awa_bbb-ccc'>
| CamelCase<'_Awa_bbb-ccc'>
| CamelCase<'-Awa_bbb-ccc'>
;
@kdmadej
Copy link
Author

kdmadej commented Feb 12, 2021

This might be a bit computationally expensive ๐Ÿ˜… so use at your own discretion ๐Ÿ˜„

Strings longer than 15 will trigger an error:

Type instantiation is excessively deep and possibly infinite.ts(2589)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment