how to use the ismatchwith function from the lodash library in typescript

The _.isMatchWith function from the Lodash library checks if object is a partial deep match with source using a customizer function. This function is useful when we want to compare custom properties on objects that require a specific comparison logic. Here's an example of how to use the function with TypeScript:

index.ts
import { isMatchWith, isEqualWith } from 'lodash';

interface Person {
  name: string;
  age: number;
  address: {
    street: string;
    city: string;
  };
}

const john: Person = {
  name: 'John Doe',
  age: 27,
  address: {
    street: '123 Main St',
    city: 'Anytown USA'
  }
};

const jane: Person = {
  name: 'Jane Smith',
  age: 26,
  address: {
    street: '456 Park Ave',
    city: 'Big City USA'
  }
};

const partialJane = {
  name: 'Jane Smith',
  age: 26
};

const partialJohn = {
  name: 'John Doe',
  age: 27,
  address: {
    street: '123 Main St'
  }
};

// Example customizer function that compares street name only
const streetOnly = (objValue: any, srcValue: any) => {
  if (objValue && srcValue && typeof objValue === 'object' && typeof srcValue === 'object') {
    const streetNameOnly = { street: objValue.street };
    return isEqualWith(streetNameOnly, srcValue, streetOnly);
  }
};

// Example usage of isMatchWith with customizer
console.log(isMatchWith(john, partialJane, streetOnly)); // false
console.log(isMatchWith(john, partialJohn, streetOnly)); // true
1091 chars
54 lines

In the example above, we define an interface for a Person object with nested address properties. We then define two Person objects john and jane, and two partial matches partialJane and partialJohn, which we'll use to compare them.

Next, we define a customizer function streetOnly that filters by street only. We wrap the comparison of the street property in an isEqualWith statement because we need to recurse through the nested objects. Finally, we test our function by comparing john to partialJane and partialJohn, respectively.

gistlibby LogSnag