Is there a way to create a function that can map object keys from camelCase to snakeCase, and be used multiple times with different objects?
I have already written a function called mapKeysToSnakeCase
which does the job, but I'm curious if there is a better way using generic types instead of just relying on any
.
Any suggestions on how this can be achieved?
export function mapKeysToSnakeCase(data: any): any {
return mapKeys(data, (value, key) => snakeCase(key));
}
Before:
const camelCase = {
firstName: 'John',
lastName: 'Smith',
};
After:
const snakeCase = {
first_name: 'John',
last_name: 'Smith',
};
@edit
I previously attempted a new type definition as suggested in the first answer, but encountered warnings in usage context. This is why I am exploring options using generic types.
sync getData(): Promise<X> {
(...)
return mapKeysToSnakeCase(camelCaseX);
}
error:
TS2741: Property 'first_name' is missing in type 'KV' but required in type 'X'.