Imagine having a defined object type, for example:
interface A {
foo: string;
bar: number;
baz: boolean;
// …
}
Is there a way to use a generic type to completely change its structure while maintaining the key-value relationship?
One possibility could be to create { key, value }
objects like this:
type KeyValueObject =
| { key: 'foo'; value: string; }
| { key: 'bar'; value: number; }
| { key: 'baz'; value: boolean; }
// | …
Alternatively, you could define a function that takes in these key-value pairs as arguments:
type KeyValueHandler =
| (key: 'foo', value: string) => Promise<string>
| (key: 'bar', value: number) => Promise<number>
| (key: 'baz', value: boolean) => Promise<boolean>
// | …
I initially thought that mapped types might provide a solution, but I couldn't quite grasp how to apply them in this scenario.