What is the best way to retrieve the value of an object based on its key?

I'm working on a function that returns another function, and I need some guidance:

fn: <T extends Object>(key: keyof T) => (value: ???) => void

I want the type of ??? to be determined by the type of instanceOfT[key]. For instance, in the case of T={name: string; age: number}, I expect fn('name') to output (value: string) => void and for fn('age') to output (value: number) => void

Do you think this is achievable?

Answer №1

We regret to inform you that inferring the generic type of your function partially is not possible at this time. For more information, please refer to the following GitHub issues:

To address this issue, you can implement one of the workarounds listed below:

  • Utilize Curry
  • Include a dummy parameter
  • Explicitly specify all parameters as generic arguments

For further insight, please see the answer provided in In TypeScript is it possible to infer string literal types for Discriminated Unions from input type of string?

namespace Curry {
  type Consumer<K> = (value: K) => void;

  function makeConsumer<P>()/*: <K extends keyof P>(key: K) => Consumer<P[K]>*/ { 
    function factory<K extends keyof P>(key: K): Consumer<P[K]> {
      return (value: P[K]) => console.log(value);
    }
    return factory;
  }
  const barConsumer = makeConsumer<{ bar: string }>()("bar");
}


namespace Dummy {
  type Consumer<K> = (value: K) => void;

  function makeConsumer<P, K extends keyof P>(dummy: P, key: K): Consumer<P[K]> { 
    return (value: P[K]) => console.log(value);  
  }
  type T = { bar: string };
  const barConsumer = makeConsumer(null! as T, 'bar');
}


namespace AllParamsInGeneric {
  type Consumer<K> = (value: K) => void;

  function makeConsumer<P, K extends keyof P>(): Consumer<P[K]> { 
    return (value: P[K]) => console.log(value);  
  }
  const barConsumer = makeConsumer<{ bar: string }, 'bar'>();
}

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

What is the process for integrating Typescript into a Quasar 2 project that is utilizing Vite as its build tool?

The Quasar 2 documentation provides in-depth guidance on integrating Typescript with Webpack: Unfortunately, my Quasar project is configured with Vite and I am struggling to locate resources on incorporating Typescript into an already existing project. A ...

Is it compatible to use Typescript version 2.4.2 with Ionic version 3.8.0?

Is it compatible to use Typescript 2.4.2 with Ionic 3.8.0? $ ionic info cli packages: (C:***\AppData\Roaming\npm\node_modules) @ionic/cli-utils : 1.18.0 ionic (Ionic CLI) : 3.18.0 global packages: cordova (Cordova CLI) : not insta ...

Taunting a specific occurrence inside a group

Good evening, I am currently in the process of developing tests for the TypeScript class shown below. My goal is to create a test that ensures the postMessage method of the internal BroadcastChannel is called. However, I am facing difficulties in setting ...

Troubleshooting the "Request failed with status code 500" error when refreshing a page in a React application

Every time the page is reloaded, an error message pops up saying: Uncaught (in promise) Error: Request failed with status code 500. Here's the code in list.tsx: const [state, setState] = useState([]); const { getRoom } = useRoom(); const fe ...

Guide for retrieving a user object from an HTTP request

I am looking to retrieve only the user object from the request. public async getUserByHash(hash: IHash) { this.logger.log('Hash for check email accessed'); const user = await this.hashRepository.findOne({ select: ['id', ...

What is the process for extracting the elements of an array fetched from a service in Angular 2?

Currently, I am learning Angular 2 + PrimeNG and going through a quick start project available at the following link: https://github.com/primefaces/primeng-quickstart The project is a CRUD application and it functions flawlessly. The data is neatly displa ...

Converting Antdesign's Datepicker to Typescript

I'm having trouble figuring out how to properly annotate the dateObj parameter in the handleDateChange function that I've created. App.tsx import { useState } from 'react'; import logo from './logo.svg'; ...

Tips for prohibiting the use of "any" in TypeScript declarations and interfaces

I've set the "noImplicitAny": true, flag in tsconfig.json and "@typescript-eslint/no-explicit-any": 2, for eslint, but they aren't catching instances like type BadInterface { property: any } Is there a way to configure tsco ...

The production build encountered an error after upgrading Angular due to a problem with document.documentElement.setAttribute not being recognized

Recently, I updated my application to Angular 16 and the upgrade was successful. The application is running smoothly without any issues. However, when I attempted to run the command for a production build, ng build --configuration=production I encountere ...

Unable to directly assign a variable within the subscribe() function

My goal is to fetch a single row from the database and display its information on my webpage. However, I've encountered an issue with the asynchronous nature of subscription, which prevents immediate execution and access to the data. Upon running the ...

Angular 9 - Button unable to be clicked under certain conditions

I have a webpage that contains a lot of information, and I would like to make it easier for the user to show/hide specific parts by clicking on buttons. Check out this stackblitz to see what I've done. Here's a brief summary of the code: <but ...

Generating form groups programmaticallyORDynamically

I recently utilized angular-archwizard to implement a wizard step with *ngFor However, I encountered an issue on how to create a dynamic formGroup for each step. In the code below, I managed to create a single formGroup for all steps, but my goal is to ha ...

Divide a string using multiple delimiters just one time

Having trouble splitting a string with various delimiters just once? It can be tricky! For instance: test/date-2020-02-10Xinfo My goal is to create an array like this: [test,Date,2020-02-10,info] I've experimented with different approaches, such ...

Arranging containers by invoking a function with material UI

I am completely new to material UI, typescript, and react, so if I make any mistakes or use the wrong terms please feel free to correct me. My goal is to place 4 boxes on a page, with three of them in a row and the fourth stacked below the first box. Curr ...

How to only disable checkboxes that are currently checked in Angular 8

click here to view an image**I would like to know how I can disable only the selected/checked items on a p-listbox in Angular 8. Is it possible to achieve this by adding a specific property or using CSS? Currently, when I try to add the [disabled] proper ...

I am encountering issues with running my tests using react-testing-library alongside TypeScript

Currently facing issues with react-testing-library in my TypeScript-based React project. Despite researching and following various tutorials, I am unable to resolve the problem. I have experimented with changing configurations in babel.config.js, tsconfig ...

In TypeScript, a mapped type is not allowed to define properties or methods

My challenge involves defining an interface with keys that match a specific enum key type. However, when I attempt to declare this type, I encounter the following error message: A mapped type may not declare properties or methods. Below is the code snip ...

Issue with binding background images to DIV elements in Angular 4 CSS

Here is a template example: <div [style.background-image]="profileImage" ></div> In the TypeScript file: We declare private profileImage: any; and use DomSanitizer for security. Fetching photo from service: We set this.profileImage using b ...

obtaining the value of an input using typescript (put request)

Does anyone know how to extract input values and store them as JSON? I'm having trouble with accessing the input value in this scenario. When I attempt document.querySelector("todo-text").value, it results in an error. const NewTodo: React.FC<NewT ...

``So, you're looking to retrieve a collection of objects that have a OneToMany

Is there a way to retrieve a list of objects with a OneToMany relation using TypeORM's queryBuilder? This is the desired output: { "id": 1, "firstName": "Bob", "lastName": "Sparrow", "orders": [ { "id": 1, "name": "Very Big Or ...