Home > Software design >  receive types from a array of objects value
receive types from a array of objects value

Time:11-27

i want to generate types out from a array of objects.

const names = [
  {
    name: 'Bob'
  },
  {
    name: 'Jane'
  },
  {
    name: 'John'
  },
  {
    name: 'Mike'
  },
]

the result should be look like this:

type NameType = 'Bob' | 'Jane' | 'John' | 'Mike'

i saw a lot of references, for example this enter image description here

CodePudding user response:

This can be still achieved using a combination of as const and indexed access types

const names = [
  {
    name: 'Bob'
  },
  {
    name: 'Jane'
  },
  {
    name: 'John'
  },
  {
    name: 'Mike'
  },
] as const

type NameType = typeof names[number]['name'];
// type NameType = "Bob" | "Jane" | "John" | "Mike"

TypeScript Playground

  • Related