Skip to content

Instantly share code, notes, and snippets.

@lordlycastle
Last active July 16, 2021 17:21
Show Gist options
  • Select an option

  • Save lordlycastle/76743b7dfa5f416396f2849a45223ab6 to your computer and use it in GitHub Desktop.

Select an option

Save lordlycastle/76743b7dfa5f416396f2849a45223ab6 to your computer and use it in GitHub Desktop.
Creates a new type that allows you to convert object's properties' case from `snake_case` to `camelCase`. This could be useful for reducing code duplication when you need respective model for TS code (camelCase) and REST request/response (JSON; snake_case).
type DB = {aaa_bbb: string, ccc_ddd_eee_fff: number};
type TS = {ab: string, cd: number};
declare function toTS(db: DB): TS; // etc....
type ArrayElementType<T> = T extends (infer E)[] ? E : never;
const el1: ArrayElementType<string[]> = 'hello';
const el2: ArrayElementType<string[]> = 1;
type helloLiteral = 'hello';
const hello: `${helloLiteral}` = 'hello';
type FistPart<T extends string> = T extends `${infer S}!${infer _}` ? S : never;
const testx: FistPart<'any'> = 'hello';
const testy: FistPart<'any!type'> = 'any';
type SnakeToPascalCase<T extends string> = T extends `${infer S1}_${infer S2}` ?
`${Capitalize<S1>}${Capitalize<S2>}` :
T extends `${infer S}` ? Capitalize<S> : never;
type SnakeToCamelCase<T extends string> = T extends `${infer S1}_${infer S2}_${infer S3}` ?
`${SnakeToCamelCase<S1>}${SnakeToPascalCase<S2>}${SnakeToPascalCase<S3>}` :
T extends `${infer R1}_${infer R2}` ? `${R1}${Capitalize<R2>}`
: T extends `${infer S}` ? S : never;
type DBwithCamelCaseProps = {
[Key in keyof DB as SnakeToCamelCase<Key>]: DB[Key]
}
const testCamelCaseDB: DBwithCamelCaseProps = {
aaaBbb: 'hello',
cccDddEeeFff: 42,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment