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

To use the extendWith function from the Lodash library in TypeScript, you first need to install the Lodash library by running the command:

index.ts
npm install --save lodash
26 chars
2 lines

Once you have installed the Lodash library, you can import the extendWith function and use it like this:

index.ts
import { extendWith } from 'lodash';

interface Person {
  name: string;
  age: number;
}

const person1: Person = { name: 'John', age: 25 };
const person2: Partial<Person> = { age: 30 };

const result = extendWith(person1, person2, (objValue, srcValue) => {
  if (typeof objValue === 'undefined') {
    return srcValue;
  }
});

console.log(result);
351 chars
18 lines

In this example, we are extending person1 with the values from person2. The objValue parameter in the callback function is the value in person1 and the srcValue parameter is the value in person2. We are checking if objValue is undefined and returning srcValue if it is.

The output of this code will be:

index.ts
{ name: 'John', age: 30 }
26 chars
2 lines

which shows that the extendWith function has successfully extended person1 with the age value from person2.

gistlibby LogSnag