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

To use the hasOwnProperty function from the Underscore library in TypeScript, you would need to first ensure that you have installed and imported the Underscore library. Assuming you have done that, you can then make use of the hasOwnProperty function as follows:

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

const obj = {a: 1, b: 2, c: 3};

// Check if obj has own property 'a'
if (_.hasOwnProperty(obj, 'a')) {
    console.log("obj has property 'a'");
} else {
    console.log("obj does not have property 'a'");
}

// Check if obj has own property 'd'
if (_.hasOwnProperty(obj, 'd')) {
    console.log("obj has property 'd'");
} else {
    console.log("obj does not have property 'd'");
}
416 chars
18 lines

In the code above, we are first importing the Underscore library using the import * as _ from "underscore"; statement. We then create an object obj with properties a, b, and c. We are then checking if obj has an own property a and d by calling the _.hasOwnProperty(obj, propName) function. If obj has the given property, the function returns true, otherwise it returns false. We then log appropriate messages to the console based on the returned values.

gistlibby LogSnag