Skip to content

Instantly share code, notes, and snippets.

@ryangoree
Created November 5, 2023 19:37
Show Gist options
  • Save ryangoree/fc594742abfa289badce5161e7b2af0a to your computer and use it in GitHub Desktop.
Save ryangoree/fc594742abfa289badce5161e7b2af0a to your computer and use it in GitHub Desktop.
Generic hyphen-case to CamelCase util and type
/**
* Converts a hyphenated string to camel case.
*
* @example
* camelCase('foo-bar') // 'fooBar'
*/
export function camelCase<S>(str: S): CamelCase<S> {
return (
typeof str === 'string'
? str.toLowerCase().replace(/-+([^-])/g, (_, c) => c.toUpperCase())
: str
) as CamelCase<S>;
}
export type CamelCase<S> = S extends `${infer T}-${infer U}`
? `${Lowercase<T>}${Capitalize<CamelCase<U>>}`
: S extends string
? Lowercase<S>
: S;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment