Papa_fern Papa_fern - 4 years ago 91
TypeScript Question

Given an arbitrary object check that the object has a given key and if it does return the value for that key in typescript

Given an arbitrary object I would like to check that it is of this form.

obj = {WHERE:{antherObject},OPTIONS{anotherObject}}

I can check if the object has the key using

but after that how do I access the value of the key?

I was thinking something like this.

validateForm(obj: Object):Object {

if obj.hasOwnProperty("WHERE") {
//return the value of "WHERE"
throw new Error("WHERE isnt a key in this object");}

Answer Source

In javascript (and typescript) there are two ways to access object properties:

  1. Dot notation, eg obj.WHERE
  2. Bracket notation, eg obj['WHERE']

You'll generally use dot notation when you know what key you're looking for. You have to use bracket notation when you are using a variable or dynamically generated value as the key.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download