determine the keys of the object properties stored in an array

Is there a method to generate an array-like list of potential values consisting of object property values within an array?

Here is an example object:

const columns: SomeType[] = [
  {
    name: "first",
    someProp: true
  },
  {
    name: "second",
    someProp: true
  },
  {
    name: "one more",
    someProp: true
  },
];

I am looking for a function that takes a string representing the values of the name property of objects in the array:

function someFunc(column: TypeThatILookingFor) {
  // perform actions
}

I want the result of columns.map(item => item.name) to be a type, and the function should only accept a value that is one of ['first', 'second', 'one more'].

Answer №1

If you want to retrieve both the order and the specific literal types of the name properties from the columns array, annotating the type as an unordered SomeType[] will make you lose track of the order. Changing it to a tuple may help, but then you'll need to specify the string literal types for the name properties in each tuple element, creating a complex and redundant type.

Instead of annotating the type, you can infer it from the initializing value using a const assertion to retain the order and literal types:

const columns = [
  { name: "first", someProp: true },
  { name: "second", someProp: true },
  { name: "one more", someProp: true }
] as const;

/* const columns: readonly [{
    readonly name: "first";
    readonly someProp: true;
}, {
    readonly name: "second";
    readonly someProp: true;
}, {
    readonly name: "one more";
    readonly someProp: true;
}] */

IntelliSense will show that columns now has all the necessary information.


To extract only the name property types, a utility type called NameMap<T> can be created. It takes in a generic arraylike type T with elements having a string-valued name property, and returns an arraylike type of just those name property types:

type NameMap<T extends readonly { name: string }[]> =
  { [I in keyof T]: T[I]['name'] }

This is a mapped type that produces an array/tuple type. It extracts the type of the name property for each element in the input type T.

Testing it:

type TypeThatILookingFor = NameMap<typeof columns>;
// type TypeThatILookingFor = readonly ["first", "second", "one more"]

The output is as expected, providing the necessary type information.

By defining a function someFunc that accepts the extracted TypeThatILookingFor, you can ensure proper type checking when passing in values:

someFunc(["first", "second", "one more"]); // okay;
someFunc(["first", "next", "one more"]); // error!
someFunc(["first", "second"]); // error!

The types are enforced correctly, ensuring the integrity of the data being passed.

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

A React component featuring a nested map function should always include a "unique key" prop for each element

I am trying to figure out how to assign a proper Key Value in this component: {var.map((building, index) => { const handles = building.buildingVertices.map((point) => { return ( <DrawingHandle key={`${i ...

What is the method in XState to trigger an event with the parameters send('EVENT_NAME', {to: 'a value from the context'})?

I want to send an event to a different spawned state machine using its ID, which I have stored as a string in a variable within the context. This state machine is neither the parent nor child. For example: context.sendTo = 'B_id' How can I use ...

Issue: Headers cannot be modified after being sent to the client - Node.js with Express and TypeScript

Greetings. I'm encountering the "Cannot set headers after they are sent to the client" error when trying to use res.redirect. This specific section of the code is triggered by a verification email. Everything works smoothly until the redirect step, w ...

Is it possible to update duplicated records in Firestore using a cloud function when there are changes made to the document

In my Firestore setup, I have the following structure: Users / uid / following / followingPersonUid / Users / uid / followers / followerPersonUid / When User A follows User B, User A is added to the followers sub-collection of User B and User B is added ...

Storing a variable in Cypress with Typescript for use in the afterEach teardown step

Throughout my test cases, I store data in a variable to be used consistently. The variable maintains its value until the very end of the test, but when trying to access it in the @afterEach teardown function for global clean up, it appears empty. It seems ...

How to Retrieve an Array from a Promise Using Angular 4 and Typescript

I am encountering difficulties when trying to store data from a returned promise. To verify that the desired value has been returned, I log it in this manner: private fetchData() { this._movieFranchiseService.getHighestGrossingFilmFranchises() ...

The EXIF-JS data is becoming inaccessible beyond the method's scope

Currently, I am in the process of developing a web application using Angular 8. My main objective is to access the exif data of an input image outside the getData method by assigning the obtained data to a global variable. However, when attempting to acces ...

How to retrieve the data from an inactive text field with a button click in an angular application?

Currently, I am working on an angular application and I'm looking for a way to copy text when a button is clicked. I need assistance in creating a function that can achieve this without relying on the clipboard API. Although I have considered using t ...

Firebase data causing issues with ion-gesture recognition?

Hey there! I'm currently facing an issue with my ionic app. I added the ion-gesture to my project, but due to the ngFor loop pulling data from Firebase, the cards are unable to move. Here's a snippet of my code: <ion-card *ngFor="let po ...

How can data be transferred from a parent to a child component in Angular?

I'm facing an issue trying to pass the selected value from a dropdownlist in a user interface. I have a parent component (app.component.html) and a child component (hello.component.html & hello.component.ts). My goal is to transfer the option val ...

Can you explain the contrast between the @HostBinding() directive and ElementRef/Renderer in Angular?

I'm currently in the process of developing a directive for a dropdown toggle feature. Through my research, I have come across two different approaches to implement this directive. Which method would be considered the most effective practice? Approach ...

Encountering a type error in Typescript when assigning a transition component to a Material UI Snackbar

Attempting to implement snackbar alert messages using Material UI in a React JS application with TypeScript. Encountering a type error when trying to modify the transition direction of the snackbar. Referenced the snackbar demo from Material UI documentat ...

Why is it that I am not receiving JSON data in my Angular application?

I am currently working on a class within a webapi public class ResponseObject { public int Success { get; set; } public string Message { get; set; } public object Data { get; set; } } Within my ASP.NetCore, I have the following method: publi ...

Having trouble retrieving an Enum within an Angular template?

I am trying to use an enum to read a property of an array. However, I encountered an error with the following code: <ng-container *ngFor="let elem of list"> <div class="ui-g-12 ui-sm-12 ui-md-12 ui-lg-12 ui-xl-12"> &l ...

Enhance the capabilities of a basic object by incorporating a superclass through the creation of

I'm currently developing a library using Typescript 2.0 that can be utilized from both Typescript and JavaScript. Within the library, there is a class called Component and a function named registerComponent, both written in Typescript. My goal is to ...

Tips on extracting a value from a subscription

I am trying to figure out how to pass a value from a subscribe function to a variable so that I can manipulate it later on. For example: getNumber: number; I need to be able to access and use the variable getNumber in the same .ts file. someMethodT ...

Create your own Angular control - rate stars - with dynamic input values

<div class="rating"> <div style="display: inline-block" *ngFor="let starred of stars; let i = index" (click)="rate(i + (starred ? (value > i + 1 ? 1 : 0) : 1))"> <ng-container *ngIf="starred; else noStar"><mat-icon class=" ...

Error encountered when utilizing a mixin in TypeScript due to a parameter issue

Recently, I delved into learning Typescript and decided to experiment with the mixin concept. The code snippet below may seem trivial, but it's all part of the learning process. Surprisingly, everything runs smoothly except for line 42, myInput.sendKe ...

My goal is to create a carousel using Vue 3 with the Composition API and TypeScript

Creating a carousel with Vue 3 and TypeScript has been quite challenging for me. I heard about using "vue-awesome-swiper" to build a carousel, but I couldn't find a tutorial on how to use it. Does anyone know how to utilize this tool effectively? Alte ...

The term 'App' is being referenced as a value when it is intended to be a type. Perhaps you meant 'typeof App'?

I am eager to master Typescript with React through hands-on experience, so I recently made the manual transition from JavaScript to TypeScript in my create-react-app. However, when working with my default testing file App.test.ts: import { render, screen ...