Home > Mobile >  How to extract union prop from an array of objects?
How to extract union prop from an array of objects?

Time:12-15

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?

Probably we can infer it somehow, or?

CodePudding user response:

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

  • Related