mardi 5 octobre 2021

When looping through an object's properties, how do I check if a key is optional?

Consider the following:

interface TestObject { param: string, foo?: string }
const object: TestObject = { 
   param: "hello"
   foo?: "bar"
}

The above has an optional parameter but, say we didn't have an interface, and the object was unknown.

How would I determine if keys were optional by looping through the property of a given object? (See below)

const takeAnObject = (object: unknown) => {
    Object.keys(object).forEach((key: string) => {
      if(key === OPTIONAL){ 
         console.log(`${key} is an optional parameter`) 
      } else { 
         console.log(`${key} is a required parameter`) 
      }
    }
}




Aucun commentaire:

Enregistrer un commentaire