Updating part of an object using TypeScript

I am looking to create a utility function that takes an instance and an object as input, and then updates the instance with the values from the provided object fields. Below is the code for the utility function:

function updateEntity<T, K extends keyof T>(
    entity: T,
    updateInput: { [key in K]: T[K] },
  ): void {
    return Object.keys(updateInput).forEach((key) => {
      entity[key as K] = updateInput[key as K];
    });
}

Here I have defined an instance and an update interface:

class Animal {
  name: string = 'no name';
  isMale: boolean = false;
}

type Input = Partial<{
  name: string;
}>;

const input: Input = {
  name: 'str'
};

const cat = new Animal();

updateEntity(cat, input); // This line produces an error

I am encountering the following error:

Argument of type 'Partial<{ name: string; }>' is not assignable to parameter of type '{ name: string; }'.
  Types of property 'name' are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.(2345)

I am struggling to fully understand this error message. My goal was to partially update the original instance with the given input data.

The input should be a subset of the original instance without any additional fields.

Here is a link to the playground: link

What could I be overlooking?

Answer №1

Utilize the non-null assertion technique. When interacting with the updateInput parameter, its type will appear as

{ [key in K]?: T[K] | undefined }
due to the possibility of fields being absent and set as undefined. Despite TypeScript's belief that updateInput[key] may be undefined instead of T[K], we are confident that updateInput[key] will only have the type T[K].

function updateEntity<T, K extends keyof T>(
  entity: T,
  updateInput: { [key in K]?: T[K] },
): void {
  for (const key in updateInput) {
    entity[key] = updateInput[key]!;
  }
}

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 project graph creation for NX has encountered a setback and was unable to be completed. The worker has halted with exit

I've encountered an issue with my Angular project while using nx. Upon running npm install, I received the following error: > NX Nx Daemon was not able to compute the project graph. Log file with the error: ...\node_modules\.cache ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

The default behavior of Angular-Keycloak does not include automatically attaching the bearer token to my http requests

I'm currently working on integrating keycloak-angular into my project, but I'm facing an issue with setting the bearer token as the default for my HTTP requests. "keycloak-angular": "9.1.0" "keycloak-js": "16.0 ...

Managing events like onClick for custom components in Next.js and React: A Beginner's Guide

Utilizing tailwindCSS for styling and writing code in Typescript with Next.JS. A reusable "Button" component has been created to be used across the platform. When the button is pressed, I aim to update its UI in a specific way. For instance, if there&apos ...

The tsconfig.json file does not support the path specified as "@types"

Having set up multiple absolute paths for my Next.js application, I encounter an issue where importing a component from the absolute path results in something like "../componentName" instead of "@components/componentName" when I am inside another folder. T ...

Angular not firing slide.bs.carousel or slid.bs.carousel event for Bootstrap carousel

I've searched high and low with no success. I'm attempting to detect when the carousel transitions to a new slide, whether it's automatically or by user click. Despite my numerous attempts, I have been unable to make this event trigger. I ha ...

Discover a Simple Trick to Enhance tsc Output: Unveil the Art of

When I work on a TypeScript project, I typically use the watch mode of the compiler: tsc --watch However, one issue I face is that it's challenging to identify errors in the output since they are displayed as plain text: Sometimes I don't even ...

Using TypeScript, Material UI introduces a new property to the primary object on the palette

Experimenting with the customization of MUI v5 theme has been a fun challenge in my current project. I have successfully tailored the theme to suit my requirements so far, but now I am faced with the task of adding a new property to the primary object defi ...

Updating a property value within a JSON object: Adjusting attributes in a JSON data format

How can I modify a specific key's value in a JSON array like the following example: input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}] ...

The best approach to effectively integrate TypeScript and Fetch is by following the recommended guidelines

Currently, I am in the process of learning React and Typescript simultaneously. On the backend side, I have a server set up with ApiPlatform. For the frontend part, my goal is to utilize fetch to either create or update a Pokemon along with its abilities. ...

What is the method for returning a string array?

My query is about how to return a string[]. Currently, TypeScript is throwing an error because each element of the array has a type of ( T[keyof T] extends readonly (infer InnerArr)[] ? InnerArr : T[keyof T] ). How can I accept the 'property' arg ...

Please ensure that the property name is a valid type, such as 'string', 'number', 'symbol', or 'any'

Can anyone help me convert this JavaScript file to Typescript? import React, { useState } from 'react'; import { Button } from './Button'; import { Link } from 'react-router-dom'; import './Navbar.css'; import Settin ...

How does the highlighting feature in Fuse.js includeMatches function operate?

Currently, in my Next JS/Typescript web application, I am using the Fuse.js library. However, I am still uncertain about how the includeMatches option functions for highlighting purposes. Whenever I enable this option, I receive a matches object within the ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

When attempting to execute my script, I encountered an error message stating that "TypeError: puppeteer.use(...) is not

Here is the current code that I've been working on. After switching it to a new folder, I encountered an error that wasn't present before. I made sure to reinstall all the necessary modules in the package.json file, but the issue persists. Is the ...

Is the Scope Staying Static in AngularJS 1.4 when Input Text Changes and Two-Way Binding is Enabled?

Encountering a strange issue with AngularJS 1.4 (TypeScript). The problem lies within the controller where a variable is set and displayed in an input text box. Oddly, when attempting to edit the value in this text box and clicking on a button, the variabl ...

Steps for Properly Defining Next.js getServerSideProps as a Function Declaration

I've been working on implementing getServerSideProps (additional information available here, and detailed API documentation here), but my challenge lies in utilizing it as a function declaration instead of an expression. Despite searching for relevant ...

How can you determine the number of times a particular digit appears around a specific position in a TypeScript array

(Utilizing Typescript for assistance) I am looking to determine the number of occurrences of the digit 2 surrounding a specific position within an array. The function takes in the position coordinates as parameters - param 1 for row and param 2 for column. ...

Angular2 tutorial with VS2015 may encounter a call-signature error that is expected

Currently following the Angular2 tutorial in VS2015 and encountering an issue with a warning that is impeding the compilation of one of my TypeScript files. The link to the tutorial is provided below. https://angular.io/docs/ts/latest/tutorial/toh-pt4.htm ...

Why does tsc produce a compiled file that throws an exception when executed, while ts-node successfully runs the TypeScript file without any issues?

I have written two ts files to test a decorator. Here is the content of index.ts: import { lockMethod } from './dec'; class Person { walk() { console.info(`I am walking`); } @lockMethod run() { console.info(`I am running`); } ...