I am looking to extract types from an array of objects.
const names = [
{
name: 'Bob'
},
{
name: 'Jane'
},
{
name: 'John'
},
{
name: 'Mike'
},
]
The desired result should resemble this:
type NameType = 'Bob' | 'Jane' | 'John' | 'Mike'
I have come across various references, such as this typescript-types-from-arrays
However, the examples I found typically utilize an array of strings as input source. For example:
const array = ['one', 'two',...]
which work seamlessly.
But what I aim to achieve is generating the types using array.map
in this manner:
const allNames = names.map((item) => item.name) as const;
type NameType = typeof names[number];
Unfortunately, this approach results in:
A 'const' assertions can only be applied to references to
enum members, or string, number, boolean, array, or object literals.
Here is a live demonstration of my attempt: Stackblitz
I would like to utilize the function getName()
with IntelliSense to easily identify the available names within the names
array.
For reference, it should look something like this:
https://i.stack.imgur.com/YyRkq.png