How can I turn the following type into an Array with key/value pairs?
type MyObject = {
foo: 'bar'
baz: 'qux'
}
The type I want:
type MyKeyValuePair = ['foo', 'bar'] | ['baz', 'qux']
I’ve tried various combinations of keyof etc. But it never ends up as a union type, where they first param in the array, matches up with a specific value.
>Solution :
You need to use powerful features of Typesript – employing mapped types and conditional types. Here are steps:
-
Use a helper type to convert individual keys into tuples:
type ToTuple<T, K extends keyof T> = [K, T[K]]; -
Use a mapped type to apply this helper type to each key in your object type:
type TupleMap<T> = {
[K in keyof T]: ToTuple<T, K>;
}[keyof T];
- Now you can apply
TupleMapto yourMyObjecttype to get the desired result:
type MyObject = {
foo: 'bar';
baz: 'qux';
}
type MyKeyValuePair = TupleMap<MyObject>; // ['foo', 'bar'] | ['baz', 'qux']
Good luck!