I’m new to TypeScript (and js) and this is probably basic:
const myObj = {
"name": "Johnny",
"age": 29
}
const accessProperty = (key : string) => {
if(key in Object.keys(myObj)) {
// TODO: access myObj.key...
}
}
- How do I access the property of
myObjthat is represented bykey - Is this the right way to check if
keyis indeed a property ofmyObj?
Thanks.
>Solution :
- How do I access the property of myObj that is represented by key
You can access the property via myObj[key]
- Is this the right way to check if key is indeed a property of myObj?
Someone posted a link to the optional chaining operator. This is probably the best way to go. There are times when you want to iterate through the keys of an object (mostly when you’re trying to figure out what it is) but in general it is hard to create meaningful code for keys that you’re not expecting, so again using the optional chaining operator is probably the best way to go.