Using the record key as the index for the function argument type

In my current setup, I have :

const useFormTransform = <T>(
  formValues: T,
  transform: Partial<Record<keyof T, (value: T[keyof T]) => any>>,
) => ...

This is how it's used :

type Line = { id?: string; fromQuantity: number };
const line: Line = { id: 'abc', fromQuantity: 123 };

useFormTransform(
  line,
  {
    id: f => f,
    fromQuantity: f => transformNumber(Number(f)),
  },
);

I am aiming for something like

Record<keyof T as U, (value: U) => any>
in the transform argument so that the value is strictly a number, not string | undefined | number as it currently is, since
typeof line['fromQuantity'] === 'number'

I have tried various approaches but haven't been successful yet.

Appreciate any help! :)

Answer №1

If you're looking to achieve this using Record, you'll have to create a custom mapped type instead:


const useFormTransform = <T, U extends keyof T>(
  formValues: T,
    transform: {
      [P in keyof T]: (value: T[P]) => T[P]
  },
) => {
    return null!;
}


type Line = { id?: string; fromQuantity: number };
const line: Line = { id: 'abc', fromQuantity: 123 };

useFormTransform(
  line,
  {
    id: f => f,
    fromQuantity: f => f + 1,
  },
);

Check it out in the 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

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

"Silently update the value of an Rxjs Observable without triggering notifications to subscribers

I'm currently working on updating an observable without alerting the subscribers to the next value change. In my project, I am utilizing Angular Reactive Forms and subscribing to the form control's value changes Observable in the following manner ...

Tips for sending a function as a value within React Context while employing Typescript

I've been working on incorporating createContext into my TypeScript application, but I'm having trouble setting up all the values I want to pass to my provider: My goal is to pass a set of values through my context: Initially, I've defined ...

`Can you bind ngModel values to make select options searchable?`

Is there a way to connect ngModel values with select-searchable options in Ionic so that default values from localStorage are displayed? <ion-col col-6> <select-searchable okText="Select" cancelText="Cancel" cla ...

"Is it possible to add an entire object to formData in one

I am looking to send both an image list and product data to an ASP.net api using formData. I have successfully sent the images, but now I am struggling with appending the entire object. I have come across some methods in JS like JSON.stringfy(object) or Ob ...

Build an Angular wrapper component for the phone textbox functionality

Looking to transform the Phone Mask solution below into an Angular component. Does anyone have a method to accomplish this? * Any solution that results in a similar component for a Phone textbox will suffice. Mask for an Input to allow phone numbers? ht ...

Sharing interfaces and classes between frontend (Angular) and backend development in TypeScript

In my current project, I have a monorepo consisting of a Frontend (Angular) and a Backend (built with NestJS, which is based on NodeJS). I am looking to implement custom interfaces and classes for both the frontend and backend. For example, creating DTOs s ...

Difficulties with managing button events in a Vue project

Just getting started with Vue and I'm trying to set up a simple callback function for button clicks. The callback is working, but the name of the button that was clicked keeps showing as "undefined." Here's my HTML code: <button class="w ...

trpc - Invoking a route from within its own code

After reviewing the information on this page, it appears that you can invoke another route on the server side by utilizing the const caller = route.createCaller({}) method. However, if the route is nested within itself, is it feasible to achieve this by ...

Retrieve the API output and save the information into an array

I am struggling with calling an API in my Angular application and extracting specific data from the JSON response to populate an array. Although I am able to retrieve the response, I am having trouble isolating a particular field and storing it in an array ...

Using Vue js and Typescript to automatically scroll to the bottom of a div whenever there are changes in

My goal is to automatically scroll to the bottom of a div whenever a new comment is added. Here's what I have been trying: gotoBottom() { let content = this.$refs.commentsWrapper; content.scrollTop = content.scrollHeight } The div containing ...

I'm stuck trying to figure out all the parameters for the MapsPage component in Angular 2

Currently, I am utilizing Angular2 with Ionic2 for my mobile app development. Everything was working flawlessly until I decided to incorporate a new module for Google Maps navigation. Specifically, I am using phonegap-launch-navigator for this purpose. The ...

Submit a pdf file created with html2pdf to an S3 bucket using form data

Currently, I have the following script: exportPDF(id) { const options = { filename: 'INV' + id + '.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 2, dpi: 300, letterRendering: true, useC ...

The package import path varies between dynamic code generation and static code generation

I have organized the src directory of my project in the following structure: . ├── config.ts ├── protos │ ├── index.proto │ ├── index.ts │ ├── share │ │ ├── topic.proto │ │ ├── topic_pb. ...

Getting the hang of using and translating typescript .tsx files with jsx in React-native

Recently, I have ventured into the world of React-native after having experience with reactjs+typescript. Wanting to test its capabilities, I decided to set up a simple project. My tool of choice for development is VS Code. After following a basic tutoria ...

ngFor filter based on user input

I am working on a 2-step stepper feature where I need to filter the values in my amountArray based on the age of the person. If the person is above 50 years old, display only the values 10000 and 15000. For Euro currency, show values 25000 and 50000. I att ...

Exploring potential arrays within a JSON file using TypeScript

Seeking guidance on a unique approach to handling array looping in TypeScript. Rather than the usual methods, my query pertains to a specific scenario which I will elaborate on. The structure of my JSON data is as follows: { "forename": "Maria", ...

The Children Element in Next.js and React Context with TypeScript is lacking certain properties

Encountering a mysterious error while trying to implement React's Context API in Next.js with TypeScript. The issue seems to be revolving around wrapping the context provider around the _app.tsx file. Even though I am passing values to the Context Pr ...

Leveraging TypeScript enums in conjunction with React to anticipate a string prop

Trying to enforce strict typing for a Button component in React. How can I ensure a prop has a specific string value? The current effort yields Type '"primary"' is not assignable to type 'ButtonLevel' enum ButtonLevel { Primary = ...

Dayjs is failing to retrieve the current system time

Hey everyone, I'm facing an issue with using Dayjs() and format to retrieve the current time in a specific format while running my Cypress tests. Despite using the correct code, I keep getting an old timestamp as the output: const presentDateTime = da ...