Reputation: 789
I need a function mapping camelCase object keys to snakeCase. I want to use it multiple times with different objects.
I wrote function mapKeysToSnakeCase
that works well, but I wonder if there is possible to use generic types instead of any
to improve the definition.
Any advice how it can be done?
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 tried previously with new type definition (like first answer suggested), but I end up with warning in usage context and it is why I want to use some generic types for it.
sync getData(): Promise<X> {
(...)
return mapKeysToSnakeCase(camelCaseX);
}
error:
TS2741: Property 'first_name' is missing in type 'KV' but required in type 'X'.
Upvotes: 0
Views: 1580
Reputation: 789
I ask my team mate to help me with this and he prepared best suited solution:
export function mapKeysToSnakeCase<R>(data: Record<string, any>): R {
return mapKeys(data, (value, key) => snakeCase(key)) as R;
}
well fit with context like:
sync getData(): Promise<X> {
(...)
return mapKeysToSnakeCase<X>(camelCaseX);
}
Upvotes: 1
Reputation: 82
You can define key-value type as follows:
type KV = { [x: string]: string }; // x is an key of type string and value have string type too
and use it:
export function mapKeysToSnakeCase(data: KV): KV {
return mapKeys(data, (value, key) => snakeCase(key));
}
Upvotes: 0