Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Turn object type into Array in TypeScript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to use powerful features of Typesript – employing mapped types and conditional types. Here are steps:

  1. Use a helper type to convert individual keys into tuples:

    type ToTuple<T, K extends keyof T> = [K, T[K]];

  2. 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];
  1. Now you can apply TupleMap to your MyObject type to get the desired result:
type MyObject = {
  foo: 'bar';
  baz: 'qux';
}

type MyKeyValuePair = TupleMap<MyObject>;  // ['foo', 'bar'] | ['baz', 'qux']

Good luck!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading