How can one retrieve a specific type? The combination of T[keyof T] unifies all types into one

 const obj = {
      role  : 'admin',
      user : {
        id : 1,
        name : 'vasa',
      },
    }  

const fun = <T>(obj: T):
      Record<`set${Capitalize<string & keyof T>}`, (a : T[keyof T]) => void>
      => {
      const action = {}
      for(const key in obj){
        action[key] = (value) => {console.log(value)}
      }
      return action
    }
    const action = fun(obj)
   

    // issue
    action.setRole({id: 2, name: 'bug'})

setRole is receiving the wrong type as T[keyof T] combines all types into one type when it's supposed to be:

setRole(string)

setUser(object)

Answer №1

Take a look at this scenario:

const obj = { role: 'admin', user: { id: 1, name: 'vasa', }, }

type Convert<Obj> = {
  [Prop in keyof Obj as `set${Capitalize<Prop & string>}`]: (value: Obj[Prop]) => void
}

const capitalize = <T extends string>(str: T) =>
  `${str[0].toUpperCase()}${str.substr(1)}` as Capitalize<T>;

const fun = <T extends Record<string, unknown>>(obj: T) =>
  (Object.keys(obj) as Array<keyof T & string>).reduce((acc, elem) => ({
    ...acc,
    [`set${capitalize(elem)}`]: (v: T[keyof T]) => { }
  }), {} as Convert<T>)

const action = fun(obj)



action.setRole('sdf') // ok
action.setUser({ id: 42, name: 'John' }) // ok
action.setUser('sdf') // error

key remmapping

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

Tips for resolving a typescript Redux connect error related to ActionCreatorsMapObject

Encountering typescript error: ERROR in [at-loader] ./src/app/components/profile/userProfile/_userMain.tsx:130:37 TS2345: Argument of type 'typeof "/usr/src/app/src/js/src/app/redux/actions/sessionActions"' is not assignable to parameter of ...

Unlock TypeScript code suggestions for extended objects

In my app, I use a configuration file named conf.ts to consolidate config values from other files for better organization. By merging these values, it becomes more convenient to access them using Conf.MY_LONG_NAMED_VALUE rather than Conf.SubCategory.MY_LON ...

Is there a way to convert discriminated unions to specific types (such as classes) using a factory function in Typescript?

I've been experimenting with a code snippet similar to the one below: type Node = | { type: 'Group'; children: Node[] } | { type: 'Obj'; payload: number }; class Group { readonly type = 'Group'; construct ...

Employing [style.something.px]="2" in Angular to specify the thickness of the border

Presently, I am setting the width of the element using this code format: <div [style.width.px]="size" [style.height.px]="size"></div> What I am aiming for is to utilize a comparable format but to define the border-width css attribute, such as ...

Return to the previous page with different query parameters, not the same one

When it comes to reverting state location back by 1 step in Angular, we can utilize something along the lines of this.location.back();. This method works well unless the system redirects to the same URL but with different query parameters. In such cases, ...

Having trouble changing file names in a Next.js 13 project

I've been facing an issue ever since Next.Js 13 updated the `pages` folder to a new `app` folder. Whenever I try to rename the default "Pages.tsx" file to something like "Home.tsx" or "Information.tsx", it breaks and shows a 404 Page error. The first ...

Angular FormData fails to append and upload files

I am attempting to use FormData in order to upload a file through an HTTP Request. Here is the HTML code: <ng-template #displayApp> <div class="display flex justify-content-center"> <div > <p-fileUploa ...

Issue with attaching extra headers to petition

I have been working on integrating socket.io with my Angular application. Following the steps outlined in this article, I tried to incorporate jwt based authentication for my Express server. To set the authentication headers as per the socket.io docs, I up ...

Utilize the authenticated page across various tests in Playwright for efficient testing

Starting out fresh with playwright and node.js frameworks Currently in the process of developing a framework using playwright with typescript. Everything was smooth sailing until I reached the point where I needed to run my tests sequentially on the same ...

VueJS - When using common functions, the reference to "this" may be undefined

I'm struggling to extract a function that can be used across various components. The issue is that when I try to use "this", it is coming up as undefined. I'm not sure of the best practice for handling this situation and how to properly assign th ...

What is the process for overloading a Vue component decorator in a TypeScript environment?

I enjoy using Vue with TypeScript decorators: import { Component, Prop, Vue, Watch } from 'vue-property-decorator'; @Component({ components: { .. }, ... }) ... Is it possible for me to add a custom property to pass to the decorator in this ...

Leveraging TypeScript for defining intricate tree manipulation guidelines

In my current project, I am working on enhancing a TypeScript process that is in place. The goal is to make it more strongly typed for better scalability and accuracy. The structure of the existing tree under consideration is as follows: interface Node { ...

Tips for injecting a service into a class (not a component)

Can you inject a service into a class that is not a component? Consider the following scenario: Myservice import {Injectable} from '@angular/core'; @Injectable() export class myService { dosomething() { // implementation } } MyClass im ...

Async/Await function is not behaving as intended

Our current approach involves storing short strings as keys. These keys are linked to longer values, which serve as labels. I am attempting to update the corresponding longer value for each key. However, a problem arises where console.log(record) always ...

unable to retrieve access-token and uid from the response headers

I am attempting to extract access-token and uid from the response headers of a post request, as shown in the screenshot at this https://i.sstatic.net/8w8pV.png Here is how I am approaching this task from the service side: signup(postObj: any){ let url = e ...

React-querybuilder experiencing issues with validator functionality

While utilizing the react-querybuilder, I have encountered an issue with field validation not functioning correctly. Upon reviewing this StackBlitz, it appears that when clicking on Rule and checking all fields, there are no errors present. export const fi ...

Determine the return type of a function based on the parameter type that is inferred

I am seeking to define a simple function that checks a condition and returns either a value or a default. In most cases, the default is constant, so it would be beneficial to return a union of expected and default value types to properly narrow it down at ...

Using Angular 6's httpClient to securely post data with credentials

I am currently working with a piece of code that is responsible for posting data in order to create a new data record. This code resides within a service: Take a look at the snippet below: import { Injectable } from '@angular/core'; import { H ...

Showing Information without NgFor Directives

I have successfully displayed data without using a ngFor loop. However, it is currently showing all the quote information from multiple customers. The CSS is arranged in such a way that the discount div is positioned next to the customerinfo div. Below is ...

Issue with NextJS Image Optimization in Vercel's production environment

As of now, I am developing a NextJS application that will eventually be deployed with multiple domains on Vercel. One of the key features of my application is the dynamic rendering of images. While all images display correctly in the preview environment on ...