Skip to content

Instantly share code, notes, and snippets.

@Sherex
Last active December 19, 2021 14:22
Show Gist options
  • Save Sherex/d956c35ac2e032d4b0cdeb6d99095fcc to your computer and use it in GitHub Desktop.
Save Sherex/d956c35ac2e032d4b0cdeb6d99095fcc to your computer and use it in GitHub Desktop.
A Typescript generic that converts properties (or just a string) from snake_case to camelCase

NOTE: I don't have a very good understanding of the more advanced stuff in TS, but I managed to hack this togheter. There's probably a better way to this. :)

The SnakeToCamel generic is inspired by this split generic from typescriptlang.org.

type Split<S extends string, D extends string> =
    string extends S ? string[] :
    S extends '' ? [] :
    S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] : [S];

My changes and ObjectSnakeToCamel is from reading the TS docs.

type SnakeToCamel<S extends string> =
S extends `${infer T}_${infer U}`
? `${T}${Capitalize<SnakeToCamel<U>>}`
: S
type ObjectSnakeToCamel<Type> = {
[Property in keyof Type as Property extends string ? SnakeToCamel<Property> : Property]: Type[Property]
}
const snakeObject = {
id: 123,
created_at: '123',
deleted_at: false
}
const camelObject: ObjectSnakeToCamel<typeof snakeObject> = {
id: 1,
createdAt: '123',
deletedAt: true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment