Home > Software engineering >  How to skip a 'Partial<Interface>' property based on a ternary operation result
How to skip a 'Partial<Interface>' property based on a ternary operation result

Time:02-18

I have a TypeScript interface that I am using to create an object of. In my case, I am only partially implementing the interface since not all the property are always available.

One of the property I want to populate is based on whether I have a certain value or not from a MongoDB query.

const Person {
  name: string,
  age: number
}

...

const newPerson : Partial<Person> = {
  name: result.name,
  age: result.age ? result.age : // skip property
}

Is there a way I can achieve this?

CodePudding user response:

You can use spread operator here:

const newPerson: Partial<Person> = {
  name: result.name,
  ...(result.age && { age: result.age })
}
  • Related