#Type in 2 variations (camelCase and snake_case)

4 messages · Page 1 of 1 (latest)

balmy cargo
#

I've been wondering how you're solving the following. All the objects coming from the backend are in snake_case:

{ transaction_id: string, transaction_status: string }

What I do is then remodel all objects to use camelCase keys:
{ transactionId: string, transactionStatus: string }

I need the first type for the initial data load (redux) AND there are cases where in the app, I need an immediate response from a direct call to the backend, which would come in snake_case.

The majority of the places in the app uses the second, camelCase shape of the object.

What I have been doing is defining two types:


interface ITransaction { transactionId: string; ...}```

Which is okey but some objects are quite big and it adds lots of extra code. I'm just wondering if I'm missing a trick and there's a better way of solving it without defining two separate types. Thanks
wraith hull
#

this can be done generically:

last templeBOT
#
type SnakeCaseToCamelCase<S extends string> =
  S extends `${infer T}_${infer U}` ? `${T}${Capitalize<SnakeCaseToCamelCase<U>>}`
  : S

type CamelCaseToSnakeCase<S extends string> =
  S extends `${infer T}${infer U}` ? `${T extends Capitalize<T> ? "_" : ""}${Lowercase<T>}${CamelCaseToSnakeCase<U>}`
  : S

type SnakeCaseKeysToCamelCaseKeys<T> = {
  [K in keyof T & string as SnakeCaseToCamelCase<K>]: T[K]
}

type CamelCaseKeysToSnakeCaseKeys<T> = {
  [K in keyof T & string as CamelCaseToSnakeCase<K>]: T[K]
}

type _1 = SnakeCaseKeysToCamelCaseKeys<{ transaction_id: string, transaction_status: string }>
//    ^? - type _1 = {
//        transactionId: string;
//        transactionStatus: string;
//    }
type _2 = CamelCaseKeysToSnakeCaseKeys<{ transactionId: string, transactionStatus: string }>
//    ^? - type _2 = {
//        transaction_id: string;
//        transaction_status: string;
//    }
wraith hull
#

that'd let you define only one of the two types and derive the other one from it