I have an object, where I sometime receive a value, and sometime not.
When I get this value, I can correctly assign it to the object.
I know that using myObj.hasOwnProperty('myProperty')
I can test if the property exist in a if statement. But when I read it on the line just below (which should happen only if the property is set), I get the following error:
ERROR in /my/project/my.file.ts (xx,yy): Property 'property' does not exist on type 'type'.
How can I only read the value only if it exist, and thus not get this error ?
if (myObj.hasOwnProperty('myProperty')){
doStuff(myObj.myProperty);
}
Simply use myObj['myProperty']
if (myObj['myProperty'] !== undefined) {
// here myProperty is defined (but maybe null or other falsy value)
}
As stated in comments, if you can redefined your myObj type then typing it as any
makes Typescript allow you to try whicherver property you want, then you can simple write :
if (myObj.myProperty !== undefined) {
// here myProperty is defined (but maybe null or other falsy value)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.