Jake Jackson
Jake Jackson

Reputation: 1225

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

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?

Upvotes: 0

Views: 18

Answers (1)

ldruskis
ldruskis

Reputation: 799

You can use spread operator here:

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

Upvotes: 1

Related Questions