Created
November 5, 2023 19:37
-
-
Save ryangoree/fc594742abfa289badce5161e7b2af0a to your computer and use it in GitHub Desktop.
Generic hyphen-case to CamelCase util and type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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