Last active
November 5, 2024 10:22
-
-
Save kuroski/9a7ae8e5e5c9e22985364d1ddbf3389d to your computer and use it in GitHub Desktop.
Typescript type camelCase / snake_case conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type CamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}` | |
? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}` | |
: Lowercase<S> | |
type KeysToCamelCase<T> = { | |
[K in keyof T as CamelCase<string & K>]: T[K] | |
} | |
type CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}` ? | |
`${T extends Capitalize<T> ? "_" : ""}${Lowercase<T>}${CamelToSnakeCase<U>}` : | |
S | |
type KeysToSnakeCase<T> = { | |
[K in keyof T as CamelToSnakeCase<string & K>]: T[K] | |
} |
This doesn't work for objects keys in arrays like this:
const data = {
name: 'Rocket',
parts: [ { brandName: 'starx' }]
}
Thanks for sharing!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Parsing error: Type expected.eslint