how to use the extend function from the underscore library in typescript

To use the extend function from the Underscore library in TypeScript, you need to first install Underscore:

index.ts
npm install underscore
23 chars
2 lines

Then, you can import the library and use the extend function as follows:

index.ts
import * as _ from 'underscore';

const obj1 = { name: 'John', age: 25 };
const obj2 = { gender: 'male' };

const result = _.extend(obj1, obj2);

console.log(result);
// Output: { name: 'John', age: 25, gender: 'male' }
220 chars
10 lines

The extend function merges the properties of obj2 into obj1, and returns obj1 with the merged properties. The result variable in the above example will contain { name: 'John', age: 25, gender: 'male' }.

Note that the extend function modifies the original object (obj1 in the above example), so use it carefully. If you want to create a new object without modifying the original ones, you can pass an empty object as the first parameter:

index.ts
const result = _.extend({}, obj1, obj2);
41 chars
2 lines

This will create a new object with the properties from obj1 and obj2, and leave the original objects unchanged.

gistlibby LogSnag