I am checking for the existence of an object property with a variable holding the property name in question.
var myObj; myObj.prop = "exists"; var myProp = "p"+"r"+"o"+"p"; if(myObj.myProp){ alert("yes, i have that property"); };
This is undefined
because it's looking for myObj.myProp
but I want it to check for myObj.prop
Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .
To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.
var myProp = 'prop'; if(myObj.hasOwnProperty(myProp)){ alert("yes, i have that property"); }
Or
var myProp = 'prop'; if(myProp in myObj){ alert("yes, i have that property"); }
Or
if('prop' in myObj){ alert("yes, i have that property"); }
Note that hasOwnProperty
doesn't check for inherited properties, whereas in
does. For example 'constructor' in myObj
is true, but myObj.hasOwnProperty('constructor')
is not.
You can use hasOwnProperty, but based on the reference you need quotes when using this method:
if (myObj.hasOwnProperty('myProp')) { // do something }
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Another way is to use in operator, but you need quotes here as well:
if ('myProp' in myObj) { // do something }
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With