How can you determine the data type of an object's value based on a specific key?

I have created a sample scenario where I am attempting to deduce the type of a value based on the key provided by the user.

// Custom function to update an object's value using key
export const updateValueByKey = <I>(
  obj: I,
  keyToUpdate: keyof I,
  newValue: I[keyof I] // Infers the type of all possible values, not the value of the given key
) => {
  obj[keyToUpdate] = newValue;
};

// Implementation of the function
updateValueByKey<{ id: number; name: string; isPrivate: boolean }>(
  {
    id: 123,
    name: "Some Note",
    isPrivate: false,
  },
  "id", // "id" | "name" | "isPrivate"
  "not a number" // number | string | boolean, should error because "id" requires a number
);

What measures can be taken to ensure that the entered value aligns with the type of the corresponding key?

Answer №1

If you find the need for updateValueByKey() to maintain the specific type of value passed in as keyToUpdate, then it's important for the function to be generically typed with respect to that parameter:

export const updateValueByKey = <I, K extends keyof I>(
    obj: I,
    keyToUpdate: K,
    newValue: I[K] 
) => {
    obj[keyToUpdate] = newValue;
};

This approach ensures the expected behavior (assuming there is no manual specification of I required during invocation, since passing a value of type

I</code allows the compiler to infer it seamlessly):</p>
<pre><code>updateValueByKey(
    {
        id: 123,
        name: "Some Note",
        isPrivate: false,
    },
    "id",
    "not a number" // error! Argument of type 'string' is 
    // not assignable to parameter of type 'number'.
);

Link to live code demo

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

Accessing React.FC in Another File with TypeScript - A Step-by-Step Guide

code - const Exne: React.FC <IProps> = ({x}) => { console.log('input', x); const [getx, assignx] = useState(x); console.log(getx, assignx); return(getx) }; Could you please provide instructions on how to acc ...

I'm having trouble with my TypeScript type declaration file not functioning properly

After trying to publish my first TypeScript NPM package and encountering issues with type recognition in my Node.js project, I realized that the type files for my package were not functioning properly. While my project structure includes files like "easyer ...

What is the method for converting a JSON string into an [object][object] format using Angular 6?

Is there a way to transform the data shown below into the [[object][object]] structure using Angular 6? resultArray = [{Q_id: "5bbee2fbbb34b98be0464c73", opt_id: 111},{Q_id: "5bbee2fbbb34b98be0464c73", opt_id: 113}] ...

Switch the display based on user interaction in Angular2

Looking for assistance with changing the view in my Angular2 template: <td *ngIf="hour === first">{{obj[0].from}}</td> <td *ngIf="hour === second">{{obj[1].from}}</td> <td *ngIf="hour === third">{{obj[2].from}}</td> Th ...

When utilizing a property on "this" within a function defined in a constructor, the compiled JavaScript code produces an undefined result

Currently, I am in the process of creating a prototype where my objective is to develop a webservice using the express framework in TypeScript, compile it to TS, and host it within a firebase functions environment. The code structure includes a Controller ...

The interface 'IProduct' does not include several properties found in type 'IProduct[]', such as length, pop, push, concat, and many more

My goal is to transfer data between parent and child components using React and TypeScript. I have defined the following interfaces: export interface IProduct { id: string; name: string; price: string; image: string; ...

ExpressJs Request Params Override Error

I am currently utilizing express version 4.19.2 (the latest available at the time of writing) This is how I have declared the generic type Request interface ParamsDictionary { [key: string]: string; } interface Request< P = core.ParamsDictionary, ...

Angular 7's innovative method for handling singleton instances: Dynamic provider

In my Angular application, I have the ability to display lists of videos or articles along with their details. There are two main components: ContentListPage and ContentDetailsPage, which serve the same purpose for both videos and articles. The only diff ...

Generating TypeScript declarations for legacy CommonJS dependencies with the correct "module" setting

One of my challenges involves creating type declarations for outdated dependencies that produce CJS modules and lack typings. An example is the aabb-3d module (although this issue isn't specific to that particular module). To generate the declaration ...

Tips for choosing the most recent entry for each category in a MongoDB database using typescript and mongoose

My mongoDB collection is structured like this: [ {user: "joe", event: "foo", timestamp: 1}, {user: "meg", event: "blah", timestamp: 2}, {user: "rick", event: "bork", timestamp: 3}, {user: "joe", event: "bing", timestamp: 4}, {user: "meg", event: " ...

Utilize the forEach method with a TypeScript wrapper class containing a list

After replacing a list with a wrapper class that allows for monitoring changes to the list, I noticed that I can no longer use the forEach statement to iterate over the class. let numberList = new EventList<number>([1,2,3,4]); numerList.forEach((elem ...

Managing API responses using Redux and Typescript

As a beginner in Typescript, I am struggling to integrate Redux with it. The documentation on using Redux with Typescript is confusing me. I am attempting to fetch data and dispatch it to my reducer for future use, just as I did before adopting Typescript ...

A simple guide on how to send an Angular component to the Nebular dialog service

My current project involves creating a web dialog in Angular6 using Nebular components. Initially, I used the method of passing an <ng-template> reference in the following manner: openAddDialog = (dialogTemplate: TemplateRef<any>) => { ...

Error alert: TypeScript typings issue - Naming conflict with Promise / Failure to locate name Promise

I am currently working on a client/server JavaScript application and I am facing a significant issue with Promises. It appears that they are either undefined or duplicated, and this problem seems to be related to the @types package. npm install --save @ty ...

What could be causing the error in my Angular code that reads "cannot read property of undefined"?

I am working with a web API to retrieve data in JSON format. The data is returned successfully, but when I try to loop over it, I encounter an error stating 'Cannot read the property of undefined CustomerName'. [System.Web.Http.HttpGet] ...

Updating a component's value in Angular 6 when there is a change in the corresponding service

My objective sounds straightforward, but I am struggling to implement it: I want one of my components to automatically update when a variable in a service changes. To illustrate my issue, consider the following example: Imagine having a service that incr ...

Encountering a 500 error code while attempting to send a post request using Angular

Whenever I attempt to send a post request to Django server, I encounter a 500 (Internal Server Error) response. Interestingly, the get and put requests work flawlessly on the same server where Django is connected to PostgreSQL database. Here is a snippet ...

The index access result is not inferred when intersecting a Record with a generic key that extends a template literal

Essentially, (T & Record<K, U>)[K] should result in U, but it encounters issues when K is generic and extends a template literal. function foo3< K extends `a${string}`, >(k: K) { const a = {} as {b: 1} & Record<K, string> ...

Switch on ngbAccordion via TypeScript File

I need to implement a function in my component.ts file that will toggle the accordion using a button. Can you help me with the script for this? This is my HTML code: <button (click)="toggleAcc()" type="button" class="btn btn-pr ...

Is "await" considered as a reserved word in ReactJS when using TypeScript?

I am trying to implement async await in my code, but I keep getting an error that says await is a reserved word. Here is the snippet of my code: public componentDidMount() { this.startDrag(); } private startDrag = async () => { const eleme ...