Skip to content

Instantly share code, notes, and snippets.

@albertms10
Last active October 18, 2024 14:18
Show Gist options
  • Save albertms10/09f14ef7ebdc3ce0e95683c728616253 to your computer and use it in GitHub Desktop.
Save albertms10/09f14ef7ebdc3ce0e95683c728616253 to your computer and use it in GitHub Desktop.
TypeScript type to convert camel-cased strings to kebab-cased
/**
* Converts the given string from camel-case to kebab-case.
* @template T The string to convert the case.
* @see https://gist.github.com/albertms10/09f14ef7ebdc3ce0e95683c728616253
* @example
* type Kebab = CamelToKebab<'exampleVarName'>;
* // 'example-var-name'
*/
type CamelToKebab<S extends string> = S extends `${infer T}${infer U}`
? U extends Uncapitalize<U>
? `${Uncapitalize<T>}${CamelToKebab<U>}`
: `${Uncapitalize<T>}-${CamelToKebab<U>}`
: '';
@johnsonjo4531
Copy link

Thanks for this. The inverse comes in handy sometimes too, so just sharing here:

type KebabToCamel<T extends string> = T extends `${infer H}-${infer J}${infer K}`
  ? `${Uncapitalize<H>}${Capitalize<J>}${KebabToCamel<K>}` 
  : T;

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