Combining keys in Typescript without overlapping

I'm working on a function that takes two objects and creates a new object with a unique set of properties. The keys from both objects are merged, but if there are common keys, the index of the object they came from is added as a suffix. I'm struggling to correctly define the return type for this function. Here's an example:

export function disjointUnion<
  T extends Record<string, any>,
  U extends Record<string, any>
>(obj1: T, obj2: U) {
  const seenKeys = new Set<string>();
  const result = {} as Record<string, any>; // Need help typing this

  for (const k of Object.keys(obj1)) {
    result[k] = obj1[k];
    seenKeys.add(k);
  }

  for (const k of Object.keys(obj2)) {
    if (!seenKeys.has(k)) {
      result[k] = obj2[k];
      continue;
    }

    result[k + 0] = result[k];
    result[k + 1] = obj2[k];
    delete result[k];
  }

  return result;
}

// Is there a way to type this as { job0: string; job1: string; age: number} ?
const obj3 = disjointUnion({ job: "developer", age: 30 }, { job: "teacher" }) ;

Answer №1

Check out this code snippet:

type Merged<T extends Record<string, any>, U extends Record<string, any>> = {
  [K in keyof T as K extends keyof U ? `${Extract<K, string>}0` : K]: T[K];
} & {
  [K in keyof U as K extends keyof T ? `${Extract<K, string>}1` : K]: U[K];
};

Feel free to view an example here.

Upon closer inspection, K in keyof T fetches all the keys from object T, and assigns them as either '${K}0' (if present in object U) or simply K (if not). It then combines these with the keys of U, tagged with "1"

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

Is NestJS the best choice for enforcing strong typing with TypeScript configurations?

My app has a main configuration expressed through environment variables (process.env). How can I expose it as one object using Next.js? In the code example below, I am able to retrieve values by keys. However, since I am passing a string, TypeScript is not ...

Angular 6's subscribe method is causing the UI to not update

I'm currently facing an issue where my component does not refresh the UI after I input data. I always have to manually refresh the page to see the changes. I suspect there might be a problem with the .subscribe method in Angular 6. Previously, when I ...

Setting up Tarui app to access configuration data

I am looking to save a Tauri app's user configuration in an external file. The TypeScript front end accomplishes this by: import {appConfigDir} from "tauri-apps/api/path"; ... await fetch(`${await appConfigDir()}symbol-sets.json`) { ... ...

Troubleshooting Issue with Mongoose Virtual Field Population

I am currently facing an issue with my database due to using an outdated backend wrapper (Parse Server). The problem arises when dealing with two collections, Users and Stores, where each user is associated with just one address. const user = { id: &q ...

setting the minimum date for a datepicker

Does anyone know how to set the minimum date for a calendar to be 2 days from the current date? For example, if today is the 27th, the minimum date should be the 29th. Any suggestions? Thanks. https://i.sstatic.net/7yHhH.png #html code <mat-form-field ...

Prevent a specific file from being compiled during karma testing sessions

For my Angular application using angular-cli with Karma, I am facing an issue where a specific file needs to be excluded from compilation during unit tests. The file causing the problem is mentioned in the error message, indicating that it cannot be compi ...

Is there a way to modify the id parameter in the URL using Angular 2's ActivatedRoute?

How can I modify a parameter in the URL without altering the overall address? https://i.stack.imgur.com/LOd4T.png This is the TypeScript code that I currently have: onRowClicked(event: any) { let currentIdPerson = event.data.IdPerson; } I am trying ...

Display Dynamic Navigation Links Depending on User Login Status in Next.js

I'm currently developing a project using Next.js, where I am working on dynamically rendering navigation links in the header depending on user authentication. The navigation links are managed by a NavBar component. For authenticated users, I intend t ...

Angular 7: The Pitfalls of Incorrect URL Concatenation

After navigating to a different page within my project, an unexpected 404 error with the wrong URL appears in the console. Here's what it looks like: https://localhost:4420/example.com/api/customers However, it should actually look like this: h ...

Updating the navigation item list according to the content being shown: A step-by-step guide

I currently have a navigation menu set up with the following code: <ul class="menu-left pl-3"> <li *ngFor="let period of periods; let i = index">> <a class="mb-4 fragment-link" [class.active]="selectedIndex === i" ...

What is the best way to simulate Graphql queries and disable the loader in order to test a React component when loading is set to false using Jest and Enzyme?

Currently, I am using code generation on the frontend to generate types and employing GraphQL queries to fetch data in this particular format - const { data, loading, error } = useSampleQuery({ variables: { a: 1, b: 2 } }) When it comes ...

Overtaking a property in a node_module interface: a guide

I am facing a situation where I need to modify an existing interface property in my custom type declaration file, rather than creating a new one. Despite trying various approaches, such as attempting to omit the property, I have not been successful in ach ...

Is it true that a TypeScript derived class is not allowed to have identical variable names?

Why is it not allowed for TypeScript derived classes to have the same variable name, even if these members are private? Is there another way to achieve this, or am I making a mistake? class ClassTS { private nom: string = "ClassTS"; ...

React-Webcam: What is the solution for the error "Object may be null" and how to resolve "Type null is not compatible with type string or undefined"?

I'm encountering an issue with const imageSrc = webcamRef.current.getScreenshot(); Error: Object is potentially 'null'; and src={imgSrc} <img src={imgSrc} /> Error: Type 'null' cannot be assigned to type 'string | und ...

Error message in Ionic 2: "Property is not found on type"

Currently, I am working on a project in Ionic 2 and have encountered a stumbling block with a seemingly simple task. My issue lies with a Textbox where I aim to input text that will then be displayed. I found some code on a website (http://www.tizag.com/j ...

Trouble arises when attempting to import React JSX project/modules from npm into an AngularJS TypeScript module

In the process of developing a proof-of-concept React framework/library, I aim to create a versatile solution that can be utilized in both React and AngularJS applications. To achieve this goal, I have initiated two separate projects: - sample-react-frame ...

Is there a way to prevent the user from proceeding to the next step if they haven't finished the initial one?

After successfully creating a multi-step form using shadcn, react-hook form, and zod, I encountered an issue. Even if I haven't completed the input fields, I can still proceed to the next step by clicking the next button. Appointment.ts export const ...

Is there a library available for asserting arrays and single values in a function that returns a union type of either an array or a single value?

Is there a library solution available for handling type narrowing in typescript projects? I'm looking for more hacks like findOrReject that can process both single and multiple objects efficiently. I've encountered issues with type narrowing and ...

The Angular NgFor directive can only be used to bind data to Iterables like Arrays

I am encountering an issue when attempting to iterate through and display data using ngFor. The specific error appearing in the console is "Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only su ...

NextAuth credentials are undefined and authentication is malfunctioning in React

I encountered the following issue: https://i.sstatic.net/3VBoJ.png This is the code snippet that I am using: return ( <> {Object.values(providers).map((provider) => { if (provider.id === "credentials") { ret ...