Develop a universal set function

Trying to come up with a suitable title for this question has been quite challenging.

The goal is to create a function that takes an Interface as a Generic and a string representing a key of that Interface. This function should return another function that can accept a parameter properly typed as (Interface[Key]).

export const createFunction = <T extends Record<string, any>>(
  key: keyof T,
): (value: ?????) => void => (value) => {
  // Do something with value
};

I experimented with a function type but couldn't get it to work

type Getter<T extends Record<string, any>> = <Key extends keyof T>(
  key: Key,
) => (value: T[Key]) => void;

Answer №1

It seems there might be some confusion with the question - is this the solution you are looking for?

const generateSetterCreator = <T extends Record<string, any>>() => {
  return <K extends keyof T>(key: K) => (value: T[K]) => {
    // Implement functionality here
  }
};

interface UserData {
  name: string;
}

// Using Interface as a generic parameter
const setterCreator = generateSetterCreator<UserData>();

// Define a key of the interface to create a setter
const nameSetter = setterCreator('name');

// Process the value associated with 'name'
nameSetter("John Doe");

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

Is there a workaround in TypeScript to add extra details to a route?

Typically, I include some settings in my route. For instance: .when('Products', { templateUrl: 'App/Products.html', settings: { showbuy: true, showex ...

Do we need to have node_modules and package.json files in order to run the dist folder in an Angular

After deleting all files in my project except the dist folder and server.js, I tried to run npm start, but it prompted that package.json & node_modules are required. My question is whether it's possible to only need the dist folder and server.js, ...

In my current project, I am working with Knockout and TypeScript but I am encountering difficulties in firing the window-resize event

Instead of using jquery, I prefer working with a custom handler for the $(window).resize(function () { ... event. If there is a way to achieve this without relying on jquery, please feel free to share it in the comments below. The code snippet below show ...

Using Firestore queries in your NodeJS application

Here's a query that is functioning as intended: const queryRef = firestore.collection('playlists').where('machines', 'array-contains', id) const snapshot = await queryRef.get() ... const playlist = document.data() as Pl ...

Developing an npm package for storing a communal instance

I am interested in developing an npm library that can be initialized with a specific set of keys and then utilized throughout an entire project. Here is an illustration of how I envision its usage: In the main component or page import customLib from &quo ...

Utilizing the Angular *ngFor directive to iterate through JSON data

Just stepping into the world of Angular, I want to share a brief overview of my goal since the code is lengthy. Here's the relevant part: Within my project, I have a list display component. And I have two components, namely animals and zone. For in ...

What steps should be taken to rectify the issue of a missing type in a property within an

After spending the last 2 years working on Angular, I am now encountering an issue with a new interface for the first time. The specific error message is as follows: Type 'MatTableDataSource<Tasks[]>' is missing the following properties f ...

tying [inactive] to a specific attribute

I have successfully implemented the functionality to disable the button when the email is in the correct format, as shown in my code below. Now, I am looking to implement the following scenario: The Get Started button should be disabled by default If a u ...

Dealing with implicit `any` when looping through keys of nested objects

Here is a simplified example of the issue I am facing: const testCase = {a:{b:"result"}} for (const i in testCase) { console.log("i", i) for (const j in testCase[i]){ console.log("j", j) } } Encountering ...

Leverage the power of the MEAN stack with Angular 2 to seamlessly retrieve data from multiple APIs

Using angular2, nodejs, expressjs, and mongodb for development. I need all APIs to fetch data and display it on an HTML page. Below is the code snippet from my .ts file. view image description here All APIs have been tested and are s ...

Is there a problem with Angular2 using TypeScript?

Currently, I am in the process of setting up my machine for Angular development by following the guidelines provided on https://angular.io/docs/ts/latest/quickstart.html As I proceeded to run "npm start" to launch my site, I encountered an issue with the ...

Automatic generation of generic types in higher-order functions in TypeScript

function createGenerator<P extends object>(initialize: (params: P) => void) { return function (params: P): P { initialize(params) return params } } const gen = createGenerator(function exampleFunction<T>(param: T) { console.lo ...

Generating an array of strings that is populated within the Promise handler

If I come across code like this in my Ionic/Angular/TypeScript project... let arr: Array<string> = []; this.databaseProvider.getAllSpecies().then(allSpecies => { for(let species of allSpecies) { if(species.name.toLowerCase().indexOf(keyword ...

What is the best way to address elements that are affected by a wrong *ngIf condition at the beginning?

I'm trying to modify the attributes and styles of DOM elements that only appear once an *ngIf condition becomes true. I'm using @ViewChild() decorator to access these elements, but I keep running into an error: Cannot read property nativeEleme ...

Angular 18: Strategies for Triggering ngAfterViewInit in OnPush Components without zone.js

Issue: After removing zone.js from my Angular 18 project to boost performance, I'm encountering an inconsistency with the ngAfterViewInit lifecycle hook in a component utilizing ChangeDetectionStrategy.OnPush. Currently, I am resorting to using Appli ...

Guide to extracting the JSON array from a JSON object with Angular

In my angular application, I have made a call to the API and retrieved a JSON object in the console. However, within this JSON object, there are both strings and arrays. My task now is to extract and parse the array from the object in the console. The JSO ...

Express server experiencing issues with generating Swagger documentation

I've been working on an Express API and decided to implement documentation using Swagger and JSDoc. However, the documentation is not working as expected. Here's how I've set it up: docs.ts: import swaggerJSDoc, { Options } from "swagg ...

Troubleshooting: Issue with Angular 2 Injectable Class not functioning properly during parameter creation and initialization

Looking to streamline API data sharing across a sample app, I attempted two versions of a Class creation but encountered issues with one of them: Version 1 [./apiKeys.ts] - working import {Injectable} from '@angular/core'; @Injectable() export ...

Previewing images with Dropzone through extending file types

Want to display an image preview before uploading using dropzone. Attempting to access the images by calling file.preview but encountering the error "it does not exist on type File." Dropzone extends the file type with a preview?: string. How can I access ...

Why isn't TypeScript acknowledging my string literal declaration?

Below is the code snippet I am working with: type Timeframe = "morning" | "afternoon" | "evening"; let myTimeframe: Timeframe = "morning"; const someValue: any = {time: "incorrect"}; myTimeframe = someValue.time; console.log(myTimeframe); I want myTim ...