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

How to extract union prop from an array of objects?

I have array of objects

const data = [{ test: 'first'}, { test: 'second'} ]

How I can get union type that looks like:

const TestType = 'first' | 'second'

from this array?

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

Probably we can infer it somehow, or?

>Solution :

So there is actually a way to do this.
For it to work though you would need to include an as const assertion to the data array.

Example:

const data = [{ test: 'first'}, { test: 'second'} ] as const
const dataForType = [...data.map(d => d.test)]

type TestType = typeof dataForType[number];

So basically we create a new array, iterate over the original data array and return the values of all corresponding test keys.
Then we create a union type that is the culmination of all these values.

Perhaps there is a shorter way to write this, but this is the gist of it.

Playground example

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