Home > Enterprise >  Checking if an object has a property and accessing it
Checking if an object has a property and accessing it

Time:08-19

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...
    }
}
  1. How do I access the property of myObj that is represented by key
  2. Is this the right way to check if key is indeed a property of myObj?

Thanks.

CodePudding user response:

  1. How do I access the property of myObj that is represented by key

You can access the property via myObj[key]

  1. 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.

CodePudding user response:

You use the dot syntax to access object fields, that don't contain restricted characters (like space or /). If your field is an arbitrary string or a variable, you can use the square brackets syntax:

return myObj[key]

You might also find optional chaining operator ?. useful, since it returns undefined instead of throwing an Error, when you are accessing an invalid object field:

const obj = {
  field: "value",
}

console.log(obj.field2); // => Error
console.log(obj?.field2); // => undefined

You can also use it with square brackets:

obj?.['someField']

CodePudding user response:

  1. myObj[key] // may be undefined or raise an error
  2. key in myObj operator in checks if the left-hand operand is a key of the right-hand operand. Calling Object.keys() will give you an array of keys, which is number-indexed and may result in a false positive if key is a number that is within array length.
  • Related