Skip to content

Instantly share code, notes, and snippets.

@fedek6
Created January 17, 2023 10:04
Show Gist options
  • Save fedek6/b5fda6ee88b15e74fb686e872e81ceca to your computer and use it in GitHub Desktop.
Save fedek6/b5fda6ee88b15e74fb686e872e81ceca to your computer and use it in GitHub Desktop.
Convert camel case object literal to snake case in TypeScript
type CamelToSnake<T extends string, P extends string = ""> = string extends T
? string
: T extends `${infer C0}${infer R}`
? CamelToSnake<
R,
`${P}${C0 extends Lowercase<C0> ? "" : "_"}${Lowercase<C0>}`
>
: P;
type CamelKeysToSnake<T> = {
[K in keyof T as CamelToSnake<Extract<K, string>>]: T[K];
};
/**
* Convert object literal with camel case properties
* to the same object with snake case properties.
* @param input
* @returns
*/
export const camelCaseObjectToSnakeCase = <T extends Record<string, any>>(
input: T
): CamelKeysToSnake<T> => {
return Object.keys(input).reduce((acc, cur) => {
const key = cur.replace(
/[A-Z]/g,
(k) => `_${k.toLowerCase()}`
) as keyof CamelKeysToSnake<T>;
acc[key] = input[cur];
return acc;
}, {} as CamelKeysToSnake<T>);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment