Issue
Let's say I have an object type, e.g.:
interface A {
  foo: string;
  bar: number;
  baz: boolean;
  // …
}
How can I transform it using a generic type into something very different while keeping the key-value relationship?
For instance, I might need { key, value } objects:
type KeyValueObject =
  | { key: 'foo'; value: string; }
  | { key: 'bar'; value: number; }
  | { key: 'baz'; value: boolean; }
// | …
or a function that accepts the 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 thought mapped types must hold the answer, but I couldn't figure out how to use them for this.
Solution
Mapped types are indeed the answer - this answer finally got me going.
A mapped type combined with a property lookup does the trick.
type KeyValueObject<T> = {
  [K in keyof T]: { key: K; value: T[K] };
}[keyof T];
// for demonstration only - the result of this is quite useless
type KeyValueAsyncTransformer<T, R> = {
  [K in keyof T]: (key: K, value: T[K]) => Promise<T[K]>;
}[keyof T];
                            Answered By - hon2a
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.