Typescript: Convert snake_case string type to PascalCase string type
Even though the string type manipulation utilities you get out of the box with Typescript are rather limited, using Typescript’s most confusing feature, the infer
keyword, you can push conversions between string types quite a lot further.
The below snippet converts string_case
string types to PascalCase
string types.
type InputType = "foo_bar_tea";
type SnakeToPascal<T extends string> = T extends `${infer A}_${infer B}`
? `${Capitalize<Lowercase<SnakeToPascal<A>>>}${SnakeToPascal<B>}`
: Capitalize<Lowercase<T>>;
type OutputType = SnakeToPascal<InputType>; // equals "FooBarTea"