What I aim to achieve
I am looking to create a JavaScript function that can remap property names of the first argument using the second argument.
The goal is to utilize this remap function to generate query string parameters. For instance, transforming
{ param1: 1, param2: 2, param3: 3}
into ?p1=1&p2=2&p3=3
.
/**
* @example
*
* const original = { a: 1, b: 'WOW', c: new Date(2019, 1, 1, 0, 0, 0) };
* const mapping = { a: 'hello', b: 'world', c: '!!!' };
*
* > remap(original, mapping);
* { hello: 1, world: 'WOW', '!!!': new Date(2019, 1, 1, 0, 0, 0) }
*/
const remap = (original, mapping) => {
const remapped = {};
Object.keys(original).forEach(k => {
remapped[mapping[k]] = original[k];
});
return remapped;
};
My flawed attempt
I made an attempt with the code below, but it has certain flaws.
export const remap = <
T extends { [key: string]: any },
U extends { [P in keyof T]: string }
>(original: T, mapping: U) => {
const remapped: any = {};
Object.keys(original).forEach(k => {
remapped[mapping[k]] = original[k];
});
// Issues
// 1. remapped is declared as any, and casting is required.
// 2. All values are declared as any.
return remapped as { [P in keyof U]: any };
};
const remapped = remap(
{ a: 1, b: 'text', c: new Date() },
{ a: 'Hello', b: 'World', c: '!!!' }
);
console.info(remapped);