A guide to implementing Typescript Generics in modifier functions

I am searching for a solution to properly enforce strong typing in the following scenario. I believe Typescript Generics might be the way to go here.

interface Person {
  name: string;
  age: number;
}

const person: Person = {
  name: "John",
  age: 30,
};

const modifyPerson = (key: keyof Person, value) => {
  person[key] = value;
}

My goal is for the 'modifyPerson' function to only accept keys from the Person interface as its first argument, and then based on that key, determine what type of value can be assigned to it.

Could you provide an example of how this can be achieved? Thank you!

Answer №1

modifyEntity has a direct connection to the entity variable. To enhance reusability with generics, it would be necessary to include that variable as a parameter in the function.

const modifyObject = <T>(object: T, property: keyof T, value: T[keyof T]) => {
  object[property] = value;
}

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

Angular HighCharts - Retrieving chart data via API

My goal is to populate the data property of my chart with values obtained from an external API: . I've defined an Interface that matches the structure of the data: export interface ChartData{ item1: number; item2: number; ...

React - A high-capacity file selector component designed to efficiently handle large numbers of files being selected

I am in search of a component that can retrieve a list of files from the user without actually uploading them. The upload functionality is already in place; I simply require a list of selected files. The component must meet the following criteria: Restric ...

Mongoose TypeScript Aggregation error: is not a valid property of type 'any[]'

Attempting to replace a standard mongo call with an aggregate call. The original code that was functional is as follows: const account = await userModel .findOne({ 'shared.username': username }) .exec(); console.log(account._id) The n ...

Tips on selecting specific text from a drop-down menu

After struggling to find a solution for retrieving the text of a selected item from a dropdown, I decided to create a common directive. This directive would allow me to easily access the text for all dropdown items when used in my code. Below is the snippe ...

Transform Promise-based code to use async/await

I'm attempting to rephrase this code using the async \ await syntax: public loadData(id: string): void { this.loadDataAsync() .then((data: any): void => { // Perform actions with data }) .catch((ex): v ...

Encountered an issue with JSON serialization while using getServerSideProps in Next.js and TypeScript to retrieve products from the Stripe Payments API

Encountered Issue on Localhost Error: The error occurred while serializing .products returned from getServerSideProps in "/". Reason: JSON serialization cannot be performed on undefined. Please use null or exclude this value. Code Sample import ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

The connections between module dependencies are unable to be resolved

I'm encountering an issue with the npm link command. Here's the scenario: I have two Angular apps - 1) app-core (published locally) 2) app-main The app-core module has the following dependencies (installed via npm): core rxjs z ...

Lack of MaterialUI Table props causing issues in Storybook

Currently, I am utilizing MaterialUI with some modifications to create a personalized library. My tool of choice for documentation is Storybook, using Typescript. An issue I have encountered is that the storybook table props are not consistently auto-gene ...

Error: Loki cannot be used as a constructor

Can anyone assist me in understanding why this code is not functioning correctly? Here's what my index.ts file in Hapi.js looks like: import { Server, Request, ResponseToolkit } from '@hapi/hapi'; import * as Loki from 'lokijs'; ...

What is the significance of `new?()` in TypeScript?

Here is a snippet of code I'm working with in the TypeScript playground: interface IFoo { new?(): string; } class Foo implements IFoo { new() { return 'sss'; } } I noticed that I have to include "?" in the interface met ...

Experiencing problems with React createContext in Typescript?

I've encountered a strange issue with React Context and Typescript that I can't seem to figure out. Check out the working example here In the provided example, everything seems to be working as intended with managing state using the useContext ...

Resolving the non-null assertion error in TypeScript and React: A step-by-step guide

My code snippet is as follows: type ItemProps = { status?: string; } <Items status={status!} /> // encountering an error with a warning about forbidden non-null assertion // @typescript-eslint/no-non- ...

Questioning the syntax of a TypeScript feature as outlined in the documentation

I have been studying the Typescript advanced types documentation, available at this link. Within the documentation, there is an example provided: interface Map<T> { [key: string]: T; } I grasp the concept of the type variable T in Map. However ...

What could be causing the elements in my array to appear as undefined?

https://i.stack.imgur.com/ze1tx.png I'm stuck trying to understand why I can't extract data from the array. const usedPlatformLog: Date[] = [] users.forEach(el => { usedPlatformLog.push(el.lastUsed) }) console.log(usedPlatformLog) // disp ...

Having trouble reloading a seekbar (input range) in Angular 7 with a function?

I am currently in the process of developing a music player using Angular 7, and below is the HTML code for my component: <div class="track-controller"> <small>{{musicPlayerService.getCurrentTime()}}</small> <div class="progress- ...

Angular 6 - Ensuring all child components are instances of the same component

My issue has been simplified: <div *ngIf="layout1" class="layout1"> <div class="sidebar-layout1"> some items </div> <child-component [something]="sth"></child-component> </div> <div *ngIf="!layout1" class= ...

How can I integrate keydown.control with a unique click function in Angular?

Is there a way to choose multiple number elements in random order and save them to an array by holding down the control key (CTRL) and clicking on the element? For example, selecting 2 and 4 out of 5. I tried different methods but couldn't figure out ...

How can I use a string from an array as a key in an object using TypeScript?

I have been utilizing a for loop to extract strings from an array, with the intention of using these strings as object keys. Although this code successfully runs, TypeScript raises a complaint: const arr = ['one', 'two']; const map = ...

What is the best way to transform an array containing double sets of brackets into a single set of brackets?

Is there a way to change the format of this list [[" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]] to look like [" ", " ", " &qu ...