2

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 typescript-types-from-arrays

but these examples always use a array of strings as resource. like:

const array = ['one', 'two',...]

which works flawless.

but what i try to do is generating the types with a array.map like this:

const allNames = names.map((item) => item.name) as const;

type NameType = typeof names[number];

but this leads into a:

A 'const' assertions can only be applied to references to
enum members, or string, number, boolean, array, or object literals.

here is a playable example of what i try to do: Stackblitz

i want to use the function getName() with IntelliSense to know which names are available in the names array. like this: enter image description here

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.