To solve this problem, we will implement recursive conditional types. The process is outlined as follows:
During each iteration, we extract the first element (K
) from the B
array and save A[K]
in a result array (R
). This procedure continues until the B
array is empty, at which point we return the final result array.
Here is the implementation code:
type MapProps<
T,
Keys extends PropertyKey[],
Result extends unknown[] = []
> = Keys extends [
infer First extends keyof T,
...infer Rest extends PropertyKey[]
]
? MapProps<T, Rest, [...Result, T[First]]>
: Result;
The type PropertyKey
encompasses any key type such as string
, number
, or symbol
.
We utilized the infer keyword to separate the first element and remaining elements in the array type.
For testing purposes, consider the following example:
type A = { a: string; b: number; c: boolean };
type B = ["b", "a"];
type C = MapProps<A, B>; // [number, string]
Try it out on the TypeScript playground