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

Time:10-06

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`) 
      }
    }
}

CodePudding user response:

You can't. At runtime, there is no type information. What you can do is create some kind of schema for your objects, and then validate them against that schema. One of the most popular packages for that is ajv

  • Related