Creating a custom Object Type based on the values of an array of objects using Typescript

I have been attempting to create a generic type (Response) that consolidates all values from KeysForResponse, specifically the values from the valueIWant property for each object in MyObject[]. I am struggling to find a solution and wondering if it is even feasible. Essentially, when I input the following array into a function:

[{valueIWant: 'makeMeAKey', foo: 'bar'}, {valueIWant: 'alsoMakeMeAKey', foo: 'bar'}]

I expect to receive the following type as output:

{makeMeAkey: string, alsoMakeMeAKey: string}

This is what I currently have, which lacks generality:

interface MyObject {
  valueIWant: string;
  nonImportantValue: string;
}

type KeysForResponse = Array<MyObject>[number]['valueIWant'];

type Response = {
  [K in KeysForResponse]: string;
};

Answer №1

In order to access the value associated with that key, you need to specify a generic parameter

type MyCustomObject<T> = {
    desiredValue: T;
}

function customFunction <T extends string, O extends MyCustomObject<T>> (request: O[]) : {[x in O["desiredValue"]]: string}  {
    return request.reduce((accumulator, current) => {
        return {
            ...accumulator,
            [current.desiredValue]: 'bar'
        }
    }, {} as {[x in O["desiredValue"]]: string})
}

const output = customFunction([{desiredValue: 'key1', bar: 'bar'}, {desiredValue: 'key2', bar: 'bar2'}]);

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

Obtaining the value of an ion-toggle in Ionic2 using the ionChange

Below is the toggle I am referring to: <ion-toggle (ionChange)="notify(value)"></ion-toggle> I am looking for a way to retrieve the value of the toggle when it is clicked in order to pass it as a parameter to the notify method. Any suggestion ...

retrieve document data from firestore using the service

Is there a way to get real-time data from a Firestore document using a service? According to Firebase's documentation, you can achieve this by following this link: https://firebase.google.com/docs/firestore/query-data/listen?hl=es#web-modular-api I ...

Learn how to set up a class using TypeScript decorators

Is there a way to automatically initialize a class when a specific decorator is present above the class? For example: @apiController export class usersControllers extends lib.baseClasses.apiControllerBase().apiController { @lib.decorators.routesRegist ...

Leveraging Angular's catchError method to handle errors and return

One of my challenges involves a model class that represents the server response: class ServerResponse { code: number; response: string; } Whenever I make api calls, I want the response to always be of type Observable<ServerResponse>, even in ...

Implementing TypeScript/Angular client generation using Swagger/OpenAPI in the build pipeline

Generating Java/Spring Server-Stubs with swagger-codegen-maven-plugin In my Spring Boot Java project, I utilize the swagger-codegen-maven-plugin to automatically generate the server stubs for Spring MVC controller interfaces from my Swagger 2.0 api.yml fi ...

Getting the first nested object within an object in Angular 8: A comprehensive guide

Looking to extract the first object from a JSON data set? In this case, we want to retrieve {"test": {"id":1, "name":"cat"}} from the following object: { "3": {"test": {"id":1, "name":"cat"}}, "4": {"test": {"id":2, "name":"dog"}}}. Keep in mind that the ...

Verify whether an object possesses all the attributes of a class in TypeScript

Within my typescript code, I have a class called abc: export class ABC{ public a : any; public b : any; public c? : any; public d? : any; } In one of my functions, I receive an input which is represented as data:any. My goal is to verify i ...

I'm trying to determine in Stencil JS if a button has been clicked in a separate component within a different class. Can anyone assist

I've created a component named button.tsx, which contains a function that performs specific tasks when the button is clicked. The function this.saveSearch triggers the saveSearch() function. button.tsx {((this.test1) || this.selectedExistingId) && ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

You cannot assign type 'Node | null' to type 'Node' when attempting to loop through HTML elements in TypeScript

In my code, I am taking a raw Markdown string stored in 'markdownString' and using the marked.js library to convert it to HTML for display on a web browser. My goal is to extract all plain text values from the page and store them in an array of s ...

Incorporating a particular JavaScript library into Angular 4 (in case the library doesn't have a variable export)

I am attempting to display the difference between two JSON objects in an Angular 4 view. I have been using a library called angular-object-diff, which was originally created for AngularJS. You can view a demo of this library here: Link I have trie ...

Deployment failure due to undetected development keys in gitignore

I have a TypeScript-coded Express server with three files for keys in the compiled and pre-compiled code: /// dev.ts - development keys const keys = { googleClientSecret: "GOOGLE_KEY", mongoURI: "mongodb+srv://MONGO_K ...

Angular 2 is having trouble identifying a component that was imported from a module

Exploring the functionalities of Angular2, I am attempting to have one module (BreadcrumbDemoModule) import the component from another module (BreadcrumbModule). At the moment, the BreadcrumbModule consists of only one component: ng2-breadcrumb. However, ...

An issue has occurred: The module named 'ApprovalModule' must be compiled using the JIT compiler, however, the necessary compiler '@angular/compiler' is not currently accessible

Issue: Error: The NgModule 'ApprovalModule' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. JIT compilation is not recommended for production environments. Consider using AOT mode instead. Alterna ...

What is the method to make a String bold when sending it through a messaging service?

Here is the structure of my service: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class MessageService { messages: string[] = []; add(message: string) { this.messages.push(message); ...

Enhance the API response for Angular service purposes

I am currently working on modifying the response returned by an API request. At the moment, I receive the response as: [ { name: "Afghanistan" }, { name: "Åland Islands" } ] My goal is to adjust it to: [ { name: "A ...

Exploring ways to fetch an HTTP response using a TypeScript POST request

I have been looking at various questions, but unfortunately, none of them have provided the help I need. The typescript method I am currently working with is as follows: transferAmount(transfer: Transfer): Observable<number> { return this.http .po ...

Is it possible to update the text within a button when hovering over it in Angular?

https://i.sstatic.net/ZhNeM.png https://i.sstatic.net/kb670.png I'm looking to update the text displayed inside a button when hovering over it, similar to the examples in these images. I have already implemented the active state, but now I just need ...

Solving the problem of cookieParser implementation in NestJS

Greetings! I have a question for you. Currently, I am working on developing a backend using NestJS, a Node.js framework. Everything is functioning smoothly except for some issues when it comes to hosting. I have created a new NestJS project and made some ...

The attribute 'map' is not found in the object 'MapPage'

I'm currently facing a challenge with integrating Google Maps into my Ionic 2 application that is based on the Tabs template. Everything was functioning properly until I attempted to initialize the this.map method within the constructor function. im ...