Definition for intersecting types

I am trying to define a function that can take two objects of different types but with the same keys:

function myFunc(left, right, keys) {
  // simplified:
  for (const key of keys) {
    console.log(key, left[key] === right[key])
  }

  return { left, right }
}

const left = {a: 1, b: 2}
const right = {b: 2, c: 3}
myFunc(left, right, ["b"])

The current implementation changes the type of the returned right, which causes issues in subsequent code after calling the function:

function myFunc<
  Left,
  Keys extends keyof Left
>(
  left: Left,
  right: Pick<Left, Keys>,
  keys: Keys[],
): {
  left: Left
  right: Pick<Left, Keys>
} {
  // ...
}

I want the returned type to remain the same:

function myFunc<
  Left,
  Right extends Pick<Left, Keys>,
  Keys extends keyof Left & keyof Right
>(
  left: Left,
  right: Right,
  keys: Keys[]
): { 
  left: Left
  right: Right
}  {
  // ...
}

However, I am getting an error about the types Left[Keys] and Right[Keys] not overlapping, which I am struggling to understand.

Any suggestions or insights?

Answer №1

An unconventional approach, but it appears to be effective in the basic example provided.

Playground Link

function myFunc<
    L extends Pick<R, (keyof R & keyof L)>,
    R extends Pick<L, (keyof R & keyof L)>,
    K extends (keyof R & keyof L)>
    (left: L, right: R, keys: K[]): { left: L, right: R }
{
    for (const key of keys) {
        console.log(key, left[key] === right[key])
    }

    return { left, right }
}
const left = { a: 1, b: 2, c: 4 };
const right = { b: 2, c: 3, d: 5 };

// Works:
myFunc(left, right, [ 'b' ]);
myFunc(left, right, [ 'b', 'c' ]);

// Error: Type '<>' is not assignable to type '"b" | "c"'.
myFunc(left, right, [ 'a' ]);
myFunc(left, right, [ 'd' ]);
myFunc(left, right, [ 'z' ]);

However, challenges may arise if the data types of the values associated with the overlapping keys do not match. Finding a solution could be complex.

In conclusion, disabling type checking for the specific === comparison line might be the best course of action.

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

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...

Service error: The function of "method" is not valid

In one of my Angular 2 applications, I have a class that contains numerous methods for managing authentication. One particular method is responsible for handling errors thrown by the angular/http module. For example, if a response returns a status code o ...

Launch a TypeScript Node.js server on Heroku deployment platform

I'm having trouble deploying a Node.js server built with TypeScript on Heroku. Despite following various tutorials and searching through Stack Overflow for solutions, I can't seem to make it work. Here is the code I have in my tsconfig.json and p ...

Having trouble importing the d3-geo package into a Node.js TypeScript project

Seeking a way to test the inclusion of specific latitude and longitude coordinates within different GeoJSON Features using code. When attempting this with: import d3 from 'd3-geo'; // or: import * as d3 from 'd3-geo' // no difference ...

Embed the getServerSideProps function within a helper method

I have multiple pages that require protection using firebase admin methods: const getServerSideProps = async (ctx: GetServerSidePropsContext) => { try { const cookies = nookies.get(ctx); const token = await firebaseAdmin.auth().verifyIdToken(c ...

Asynchronous handling of lifecycle hooks in TypeScript for Angular and Ionic applications

I'm intrigued by the idea of integrating TypeScript's async/await feature with lifecycle hooks. While this feature is undeniably convenient, I find myself wondering if it's considered acceptable to make lifecycle hooks asynchronous. After ...

What is the best way to integrate retrieved data into Next.js with TypeScript?

Hello everyone! I recently started working with Next.js and TypeScript. Currently, I'm attempting to use the map() function on data fetched from JsonPlaceholder API. Here is my implementation for getStaticProps: export const getStaticProps: GetStatic ...

Obtain the promise value before returning the observable

I'm facing an issue with the code below, as it's not working properly. I want to return an observable once the promise is resolved. Any thoughts or suggestions would be greatly appreciated. getParalelos() { let _observable; this.getTo ...

The method toLowerCase is not found on this data type in TypeScript

I am currently working on creating a filter for autocomplete material. Here is an example of my model: export class Country { country_id: number; name: string; } When calling the web method ws: this.ws.AllCountry().subscribe( ...

Having difficulty installing TypeScript on my machine

https://i.stack.imgur.com/l6COf.pngHaving trouble installing TypeScript with the following error: npm WARN registry Using outdated package data from https://registry.npmjs.org/ due to an error during revalidation. npm ERR! code E500 npm ERR! 500 Interna ...

What is the proper way to type a collection and put it into action?

I am looking for a way to create an object that mimics a set. Specifically, I want the transaction id to act as a key and the transaction details as the value. To achieve this, I created the following: type TransactionDetail = { [key: TransactionId]: Tra ...

Module 'rxjs/internal/Observable' not found

When attempting to utilize the JwtHelperService module in my service, I encountered the following error: ERROR in node_modules/@auth0/angular-jwt/src/jwt.interceptor.d.ts(3,28): error TS2307: Cannot find module 'rxjs/internal/Observable'. In my ...

Attempting to authenticate with Next.js using JWT in a middleware is proving to be unsuccessful

Currently, I am authenticating the user in each API call. To streamline this process and authenticate the user only once, I decided to implement a middleware. I created a file named _middleware.ts within the /pages/api directory and followed the same appr ...

The Vue 3 Composition API - The property retrieved by setup() "is accessed during rendering but is not defined in the instance."

I've been experimenting with Vue 3's Composition API by creating a small in-app message console, but I'm having trouble pinpointing the error in my code. When rendering this component, the state is being accessed during render (in the loop), ...

Tips for efficiently finding and comparing text within the results generated by a for loop in Angular/Javascript

In my XML data, I have extracted all the tag names using a for loop and some other logic. Now, I am looking to find the word 'author' from the output values that are displayed in the console during the loop. If any of the output values match &apo ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

Updating Angular 9 values using a fixed object

I am dealing with a patch value here where I simply pass an object to it. this.formPesquisar.controls['daniloTeste'].patchValue(this.dadosVisualizar.daniloTeste); However, I would like to pass a static object instead, something like: this.formPe ...

Troubleshooting: Issue with Button Layout in Ionic's ItemSliding Component

How can I create a list item that allows swiping to reveal an archive button? The requirement is for the icon to appear to the left of the text. I'm referring to the documentation on Button Layout: https://ionicframework.com/docs/api/components/item ...

The value stored in Ionic Storage will only be visible on the HTML page after a refresh is performed

After updating my Ionic Storage values, they are not showing up on the HTML page until I reload it. I have researched similar issues faced by others, but the solutions I found either do not work or are no longer applicable due to changes in the Ionic versi ...

Is there a way to verify if multiple variables in Typescript are null or undefined?

Background To address the issue of checking whether a specific variable is null or undefined, I created the isNullish function. The implementation of this function is shown below. type Nullish = null | undefined; const isNullish = (target: unknown): targe ...