By utilizing the built-in Uncapitalize<S>
function, you can easily convert a string like FooBar
to fooBar
:
const fooBar: Uncapitalize<'FooBar'> = 'fooBar';
However, this method proves inadequate when dealing with class names that adhere to the HTML5 convention, such as XMLHttpRequest
:
const xmlHttpRequest: Uncapitalize<'XMLHttpRequest'> = 'xMLHttpRequest';
Specifically, a type is required that can:
- Convert instances of
PascalCase
containing multiple connectedUPPER_CASE
letters forming an acronym, into astrictCamelCase
string type that makes the acronyms lowercase, - Avoiding multiple capital letter clusters.
For instance:
XMLHttpRequest
->xmlHttpRequest
HTMLAnchorElement
->htmlAnchorElement
FOOBaAAr
->foobaaAr
Since this will be used for code validation rather than transforming user input, aesthetics are not a priority, as it becomes the responsibility of the developer to rectify their naming conventions (:
It is known that the new template literal types in TypeScript, particularly their inference features, can be employed for this purpose. However, the provided examples only demonstrate one-sided inference, like ${infer Foo}bar
, and utilizing multiple inference types often results in the last one being greedy, such as
${infer FirstChar}${infer Rest}bar
.