Using a specific type of keys, attempting to set two instances of those keys simultaneously will result in an error of that type

Consider this scenario:

type Example = {
  x: string,
  y: number
}

const a: Example = {
  x: "x",
  y: 1
}

const b: Example = {
  x: "y",
  y: 2
}

const issue = (keys: (keyof Example)[]) => {
  keys.forEach(key => {
    a[key] = b[key]
  })
}

An error with code TS2322 has been encountered and it's proving difficult to troubleshoot. (or to explain in more detail).

Here is the complete error message:

Type 'string | number' is not assignable to type 'never'.

Answer №1

The issue lies in how keyof dummy specifies 'a' | 'b', without properly distinguishing between them. TypeScript lacks the intelligence to understand that if a[key] represents a string, then b[key] will also represent a property containing a string. (It currently interprets b[key] as string | number, which cannot be assigned to a value that is strictly either a string or a number, but not both.)

To address this, you must utilize generics to correctly type the key and allow for the assignment:

const problem = <T extends keyof Dummy>(key: T) => {
  a[key] = b[key];
}

If dealing with an array of keys instead, it may be beneficial to use Object.fromEntries to form a partial object beforehand, followed by employing Object.assign:

const problem = (keys: (keyof Dummy)[]) => {
  const partial = Object.fromEntries(
      keys.map(key => [key, b[key]])
  );
  Object.assign(a, partial);
}

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

What methods can I use to analyze the integrity of the data's structure?

Currently working on an API using NestJS and typeorm. I am in need of a way to verify the format of the data being returned to clients who make requests to it. For instance, when accessing the /players route, I expect the data to have a specific structure ...

Combine VS2015 preview with TypeScript 1.3 at your own risk - it may result

After installing VS2015 Preview, I decided to create an MVC project and add a new TypeScript file. However, when trying to compile, I encountered the following error message: The "TypeScript.Tasks.VsTsc" task could not be loaded from the assembly C:&bso ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

Error message in Visual Studio 2017: Identical name 'URLs' declared twice in

In our Visual Studio 2017 project, we have multiple TypeScript files that define a URLs class. Each file contains different implementations of the class to change site URLs based on the specific use case: customer/urls.ts namespace Portal { export cl ...

Steps to resolve the issue with "Error: StaticInjectorError(AppModule)[NgbDropdown -> ChangeDetectorRef]"

My attempt at creating a web app using Angular resulted in successful compilation with no errors. However, upon execution, the browser displays a blank page accompanied by the following error message: ERROR Error: Uncaught(in promise): Error: St ...

Automatic type inference for functions in TypeScript with arguments

I am looking to define an interface with the following structure: interface CheckNActSetup<D, C> { defs: (event: Event) => D, context: (defs: D) => C; exec: (context: C) => any[]; when: ((context: C) => boolean)[]; } and implement it usi ...

Allow Visual Studio Code to create a constructor for Typescript class

When developing Angular 2 apps in Typescript using Visual Studio Code, one common task is writing constructors with their parameter list. Is there a way to save time and effort on this? It would be really helpful if the IDE could automatically generate th ...

What kind of registration does React Hook Form use?

When utilizing react-hook-form alongside Typescript, there is a component that passes along various props, including register. The confusion arises when defining the type of register within an interface: export interface MyProps { title: string; ... ...

Remove the Prisma self-referencing relationship (one-to-many)

I'm working with this particular prisma schema: model Directory { id String @id @default(cuid()) name String? parentDirectoryId String? userId String parentDirectory Directory? @relation("p ...

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

Challenge: Visual Studio 2015 MVC6 and Angular 2 compilation issue - Promise name not found

Initially, I've made sure to review the following sources: Issue 7052 in Angular's GitHub Issue 4902 in Angular's GitHub Typescript: Cannot find 'Promise' using ECMAScript 6 How to utilize ES6 Promises with Typescript? Visual ...

implement a solution in Ionic 4 Angular 6 that triggers a function only when all the observables in a loop have

In my code, I have a function named getDevices(). This function is responsible for fetching an array of devices. After getting this array, the code iterates through each device and calls another function called updateToServer(). The purpose of updateToServ ...

Asynchronous retrieval of reference value from Firebase Firestore in ReactJS

Encountering a peculiar bug in TypeScript-JavaScript where I have a Model class in TypeScript and a ReactJS Component in JS. The issue arises when dealing with a list of Promo Objects, each containing a "_listCompte" property which holds a list of Compte O ...

Drizzle ORM retrieve unique string that is not a database column

I'm working with a SQL query that looks like this: SELECT * FROM ( SELECT 'car' AS type, model FROM car UNION SELECT 'truck' AS type, model FROM trucks ) vehicles; In Drizzle, I'm trying to replicate the 'car ...

Exploring the most effective strategies for creating a brand-new type in TypeScript?

In the execution environment I'm working with, there are several global constants that represent different directions: TOP = 1 TOP_RIGHT = 2 RIGHT = 3 BOTTOM_RIGHT = 4 BOTTOM = 5 BOTTOM_LEFT = 6 LEFT = 7 TOP_LEFT = 8 These constants are not just ran ...

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...

Is Angular 4 failing to set headers properly or is Express.js searching in the wrong place?

When interacting with an Express.js API, I encountered a issue regarding the handling of auth tokens. The problem arose when sending the token in the request headers using Angular 4 compared to Postman. In Postman, setting the header named 'Authorizat ...

Javascript operations for duplicating and altering arrays

In my Angular application, I am working with an array called subAgencies that is connected to a datasource. I need to implement 2-way binding on this array. Currently, I have a method in place where I copy the contents of the original array to a new one, ...

Having trouble retrieving information from combineLatest in Angular?

I'm having some trouble with fetching files to include in the post logs. It seems that the data is not being passed down the chain correctly when I attempt to use the pipe function after combining the latest data. This code snippet is part of a data r ...

A TypeScript utility type that conditionally assigns props based on the values of other properties within the type

There is a common need to define a type object where a property key is only accepted under certain conditions. For instance, consider the scenario where a type Button object needs the following properties: type Button = { size: 'small' | &apo ...