Home > front end >  How to apply generic type to a util function that compares object values
How to apply generic type to a util function that compares object values

Time:02-01

is anyone able to help me with the syntax here, am getting an error on the following line:

arr2.some((arr2Obj) => arr2Obj[identifier] === arr1Obj[identifier]) // Type 'U' cannot be used to index type 'T'

I am trying to write a function which compares two arrays of objects to check whether a specific value (in this case "id") inside the value exists in the comparison array.

type Member = {
  id: string;
  firstName: string;
  lastName: string;
};

const signedIn = [
  {
    id: uniqid(),
    firstName: "Joe",
    lastName: "Bloggs"
  }
];

const notSignedIn = [
  {
    id: uniqid(),
    firstName: "Mary",
    lastName: "Smith"
  },
  {
    id: uniqid(),
    firstName: "Trevor",
    lastName: "Small"
  }
];

function duplicateObjectInArrays<T, U>(
  arr1: T[],
  arr2: T[],
  identifier: U
): boolean {
  // return true if there is a dupe
  return arr1.some((arr1Obj) =>
    arr2.some((arr2Obj) => arr2Obj[identifier] === arr1Obj[identifier]) // Error's here
  );
}

console.log(duplicateObjectInArrays<Member, string>(signedIn, notSignedIn, "id"));

CodePudding user response:

you should use keyof as a type of parameter of key field instead of the second generic

   function duplicateObjectInArrays<T>(
      arr1: T[],
      arr2: T[],
// use keyof
      identifier: keyof T
    ): boolean {
      // return true if there is a dupe
      return arr1.some(
        (arr1Obj) =>
          arr2.some((arr2Obj) => arr2Obj[identifier] === arr1Obj[identifier]) // Error's here
      );
    }
    
    console.log(duplicateObjectInArrays<Member>(signedIn, notSignedIn, 'id'));

Here is stackblitz example https://stackblitz.com/edit/typescript-e8n4c7?file=index.ts

CodePudding user response:

Managed to get it working with help from @jcalz in the comments...

const duplicateObjectInArrays = <T,>(
  arr1: T[],
  arr2: T[],
  identifier: keyof T
): boolean => {
  // return true is there is a dupe
  return arr1.some((arr1Obj) =>
    arr2.some((arr2Obj) => arr2Obj[identifier] === arr1Obj[identifier])
  );
}
  • Related