Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save protoEvangelion/325a27cef23878b31f1dd85f1c510dc4 to your computer and use it in GitHub Desktop.
Save protoEvangelion/325a27cef23878b31f1dd85f1c510dc4 to your computer and use it in GitHub Desktop.
Converts camelCase key in interface to snake_case key
// Adapted from: https://stackoverflow.com/a/65642944/6502003
type CamelToSnake<T extends string, P extends string = ''> = string extends T
? string
: T extends `${infer K}${infer R}`
? CamelToSnake<R, `${P}${K extends Lowercase<K> ? '' : '_'}${Lowercase<K>}`>
: P
/**
* Converts camelCase key in interface to snake_case key
* Example:
* type Name = CamelToSnakeCaseKeys<{ firstName: 'Ryan' }> // { first_name: 'Ryan' }
*/
export type CamelToSnakeCaseKeys<Type> = Type extends object
? {
[Property in keyof Type as CamelToSnake<
string & Property
>]: CamelToSnakeCaseKeys<Type[Property]>
}
: Type
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment