retrieve data types from an array of object values

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

Answer №1

To accomplish this, a clever mix of as const and indexed access types can still be utilized.

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

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

Explore in TypeScript Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

reloading a webpage while keeping the current tab's URL selected

I want to incorporate a feature I saw on the jQuery website at http://jqueryui.com/support/. When a specific tab is pressed, its contents should open. However, when the page is refreshed, the same tab should remain open. I'm trying to implement this i ...

The ng-controller directive fails to function on the content of Kendo tabstrip tabs

My ng-controller is not functioning properly for the kendo tabstrip tab content. Could you please review my code below? <!--tabstripCtrl.js--> angular.module('tabstripApp',[]); var app = angular.module('tabstripApp'); app.con ...

Utilize PHP to transform JSON data into JavaScript

Hello, I am a newcomer to Stackoverflow and I need some assistance. My issue involves converting JSON with PHP to JavaScript. I am using PHP to fetch data from a database and create JSON, which I then want to convert for use in JavaScript as an object (obj ...

Step-by-step guide to enabling native Bootstrap 2.3.2 JavaScript elements within Liferay

In my web development project, I am working with Liferay 6.2 and utilizing Alloy UI's version of Bootstrap in the html pages by adding these lines: <link href="http://cdn.alloyui.com/2.5.0/aui-css/css/bootstrap.min.css" rel="stylesheet" /> < ...

Trouble with Fetching Data by ID in MongoDB 2.0.0 Driver

In my NodeJS/Express web service project, I am using the MongoDB 2.0.0 driver to interact with the database. UPDATE: Following previous feedback, I have made changes to my code, including removing the db.close() call. Everything works smoothly when I per ...

How does Socket.io facilitate a basic web socket connection with a specific URL?

My current project involves a client making a WebSocket request to the following URL: ws://localhost:3000/feed/XBTMUR https://i.sstatic.net/R7H9T.png On my server side, I am utilizing NodeJs with express running. I have decided to implement Socket.io in ...

Manipulation of every side of a cube or any other shape within three.js

Is there a way to achieve control over individual faces without manually creating a geometry? I am trying to create an explosion effect where each face moves in different dimensions. Can pre-made geometries such as cubes or polyhedrons be disassembled, or ...

strategies for chaining together multiple observables with varying data types and operations

Hey everyone! I'm facing a situation where I have a form with multiple select types, and the options for these inputs are coming from an API. I then take the data emitted from the HTTP request observable and feed it into my FormGroup, and everything i ...

What could be causing the error message "Error: Cannot modify headers after they are sent" to appear?

I am attempting to insert data into an MS SQL server when a JSON Data API POST request is made. var express = require('express'); var app = express(); var sql = require('mssql'); // Connection string parameters. var sqlConfig = { u ...

A guide on smoothly navigating to the desired row in a gridview using Asp.net

Currently, I am developing a project using ASP.net and C# technology. In my application, I integrated a GridView that contains multiple rows. Within the grid, there is a text box and a search button available. The columns displayed in the grid are Id and ...

Tips for maintaining the chat scroll position while typing on mobile devices

Check out this example page: https://codesandbox.io/s/summer-flower-uxw47?file=/index.html:4175-4223 The issue at hand is that when accessing the site from a mobile device and tapping on the input field, the keyboard pops up. This causes the text in the m ...

The ng-change event is triggered for radio buttons that are generated using ng-repeat the first time they appear, but not for subsequent appearances

Is it possible to trigger the updateRow method on every change of a radio button selection? Currently, the updateRow method is only being called the first time the radio button changes. How can I make sure it executes each time there is a change? Html: ...

Exploring the integration of PostgreSQL into JavaScript

As a beginner in JavaScript, I am looking to create a web page that can store data in a database. Can anyone provide guidance on what resources or materials I should study to learn more about this process? ...

Count the occurrences of each symbol in the Java matrix

How can we determine the frequency of each letter in a randomly filled 10x10 two-dimensional array containing both uppercase and lowercase English letters? ...

The error message "Data type must be consistent across all series on a single axis in Google Chart" may cause confusion

I'm struggling with an error message that appears when I try to run my Google chart. Here is the code I am using to generate the chart. function (resultVal) { var arrMain = new Array();//[]; for (var i = 0; i < resultVal.length; i++) { ...

After the element has been inserted, dom.byId will give you an undefined response

I have encountered an issue with a function that adds a div as a child to a dijit/layout/contentpane. The problem arises when I attempt to reference this div using dom.byId after adding it to the content pane. The function is triggered by a click event on ...

When initiating an Ionic project, you may notice a repeated message in the terminal saying, "[INFO] Waiting for connectivity with npm..."

I'm in the process of setting up a new Ionic project along with all the necessary dependencies. However, whenever I try to execute the command "ionic serve," I keep getting stuck at the continuous display of the message "[INFO] Waiting for connectivit ...

The button will continue to be enabled even if the textfield is empty

I have a task to implement a feature on a webpage where the submit button should remain disabled until all values are entered in the textbox. However, I am facing an issue where the submit button is already active when the page loads. .directive('pas ...

The element 'x' is implicitly bound with a type of 'any'

I've been exploring the world of Nextjs and TypeScript in an attempt to create a Navbar based on a tutorial I found (). Although I've managed to get the menu items working locally and have implemented the underline animation that follows the mou ...

Script - Retrieve the content of the code element

I am currently developing an extension for VS Code that will enhance Skript syntax support. One challenge I am facing is the inability to select the body of the code block. Skript syntax includes various blocks such as commands, functions, and events, eac ...