Partial is not accurately handled by Typescript generics

Encountered an issue with the function below when using typescript 3.7.2:

function updateWithPartial <T,P extends Partial<T>, K extends keyof P> ( obj: T, part: P, key: K ) {
    return obj[key]=part[key]
}

So, if key is a keyof Partial, it must also be a keyof T. Can you spot the missing piece?

Answer №1

When it comes to this scenario, key is not just simply keyof Partial<T> - its type actually extends keyof P, where P extends Partial<T>. It's important to note that P may contain different keys than T, which means that using key as a property for T is not possible in this context.

If you prefer not to add new properties to T, then there's no need for the type parameter P since it can be automatically deduced from T itself. Here are two solutions, depending on whether you want obj to receive undefined values from part or not:

// no undefined values assigned from part
function updateWithPartial<T, K extends keyof T>(obj: T, part: Partial<T>, key: K) {
  if (part[key] === undefined) throw new Error() // throw an error or handle it differently...
  return obj[key] = part[key] as T[K] // helps the compiler understand that part[key] must be defined here
}

// possible undefined values assigned from part
function updatePartialWithPartial<T, K extends keyof T>(obj: Partial<T>, part: Partial<T>, key: K) {
  return obj[key] = part[key]
}

Now, let's run some tests:

declare const foo: { a: string }

const res = updateWithPartial(foo, { a: "bar" }, "a") // string 
const res2 = updatePartialWithPartial(foo, { a: "bar" }, "a") // string | undefined
const res22 = updatePartialWithPartial(foo, {}, "a") // string | undefined

Try 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

How can I showcase a different component within another *ngFor loop?

I am currently working on a table in HTML that displays product information. Here is the code snippet for it: <form [formGroup]="myform" (ngSubmit)="submit()" > <tbody> <tr class="group" *ngFor="let item of products;"&g ...

The value from select2 dropdown does not get populated in my article in Angular

I am attempting to link the selected value in a dropdown menu to an article, with a property that matches the type of the dropdown's data source. However, despite logging my article object, the property intended to hold the selected dropdown value app ...

An angular component that is functioning properly when connected to a live server, however, it is experiencing issues when trying to run `

I tried integrating versitka into my Angular component by placing the version HTML file and all necessary assets in the appropriate directories. However, when I run ng serve, only the HTML file seems to be working, while the CSS and images fail to load. I ...

What is the best technique for verifying the existence of data in the database before making updates or additions with Angular's observables?

I am facing a straightforward issue that I need help with in terms of using observables effectively. My goal is to search my database for a specific property value, and if it exists, update it with new data. If it does not exist, then I want to add the new ...

Exploring NuxtJS Vuex Module namespaces and mutation enumerations

My NuxtJS website has a Vuex store with a root state and a module located at store/shop/cart/state.ts. Within the module, there is a file called store/shop/cart/mutations.ts. import { MutationTree } from 'vuex'; import { CartState } from './ ...

Encountering a sign-in issue with credentials in next-auth. The credential authorization process is resulting in a

I am currently facing an issue with deploying my Next.js project on Vercel. While the login functionality works perfectly in a development environment, I encounter difficulties when trying to sign in with credentials in Production, receiving a 401 error st ...

Creating a personalized button in DraftJs for inserting customized HTML with CSS styles

When utilizing DraftJs with WYSWYG, my task involves creating a custom button in the toolbar. Upon clicking this button, I intend to insert custom HTML (containing <button>) directly into the content. While I am familiar with adding a custom button ...

Combining enum values to create a new data type

Exploring the implementation of type safety in a particular situation. Let’s consider the following: const enum Color { red = 'red', blue = 'blue', } const enum Shape { rectangle = 'rectangle', square = 'square ...

What is the method for defining a mandatory incoming property in an Angular2 component?

In my current project, I am developing a shared grid component using Angular2 that requires an id property. export class GridComponent { @Input() public id: string; } I'm looking for a way to make the id property mandatory. Can you help me with ...

While not all attributes of the response object are null, there are certain object attributes that are displayed as null

My component is responsible for displaying data in a table that is fetched from Firestore. Although the data retrieved is complete, I am noticing that the settings attribute is often null when accessed in JSX. Occasionally, I do see the correct output, but ...

Encountering a warning message in Vue 3 Migration Build using Typescript: Error in finding export 'default' (imported as 'Vue') within the 'vue' package

I've been working on migrating my vue2 application to Vue3 using the Migration Build. I diligently followed the steps outlined in the documentation available at https://v3-migration.vuejs.org/migration-build.html, but despite that, I still keep encoun ...

Tips for passing multiple items for the onselect event in a ng-multiselect-dropdown

I've got a multi-select dropdown with a long list of options. Currently, when I choose a single item, it triggers the Onselect event and adds data from the newArrayAfterProjectFilter array to the myDataList based on certain conditions in the OnselectE ...

Determining in Angular 8 whether a value has been altered by a user or by a method call

Within my select element, the value is currently being assigned through an ngOnInit call. Here is an example of the HTML code: <select name="duration" [(ngModel)]="exercisePlan.duration" (ngModelChange)="onChange($event)"> <option *ngFor="l ...

Retrieving the value of a variable within an object using an Observable

Can someone help me figure out how to assign a variable to a value inside an object in an Observable in my typescript file? I can retrieve the variable's value in my HTML file, but I seem to be missing something crucial. I believe the solution may inv ...

Issue with routing in a bundled Angular 2 project using webpack

Having a simple Angular application with two components (AppComponent and tester) webpacked into a single app.bundle.js file, I encountered an issue with routing after bundling. Despite trying various online solutions, the routing feature still does not wo ...

Deactivating PrimeNG checkbox

I am currently facing an issue with disabling a PrimeNG checkbox under certain conditions by setting the disabled property to true. However, whenever I click on the disabled checkbox, it refreshes the page and redirects me to the rootpage /#. To troublesh ...

When working with environment variables in Node.js, everything runs smoothly within the console log. However, an error occurs when attempting to pass a parameter to

In my current project setup with nx monorepo and TypeScript for handling environment variables in Node.js, I encountered a peculiar issue. I am able to access the variables using console.log, but when I pass the variable as a parameter to the mongoose.conn ...

Strategies for updating JSON file content as data evolves

I am facing an issue with loading a json file that populates charts. The file is generated from external data sources and stored in the asset directory. Is there a method to automatically load the updated json file? I have attempted to include the code fo ...

Issue encountered when attempting to import a module within the ionic framework

I encountered an issue in my project (built with the ionic-framework 3) where I included the following line to import the dialogflow module: const dialogflow = require('dialogflow'); However, when compiling, it resulted in the error message: ...

Using Typescript, the type T or a function that returns T can be utilized in various scenarios

You can check out a demonstration on this interactive platform. In creating a simple generic type that represents either a variable or a function returning a variable, there was an issue with the typical typeof arg === 'function' check. The erro ...