Home > Blockchain >  Convert an optional field from (RelatedModel | undefined)[] to RelatedModel[] using filter
Convert an optional field from (RelatedModel | undefined)[] to RelatedModel[] using filter

Time:02-13

I'm having trouble satisfying typescript in the following scenario.

interface Part {
  id: number
  relatedModel?: RelatedModel
}

const parts: Part[] = [ /* list of parts ... */ ]

const relatedModels = parts
  .map(part => part.relatedModel)
  .filter(relatedModel => relatedModel)

Typescript thinks relatedModels has type (RelatedModel | undefined)[] but should be RelatedModel[] due to the filter. I believe what I've done is valid but Typescript isn't understanding the filter().

Is there some other way of doing this?

Note, the following works but is just a lot more verbose.

const relatedModels = parts
  .map(part => part.relatedModel)

const newRelatedModels: RelatedModel[] = []

for (const relatedModel of relatedModels) {
  if (relatedModel) {
    newRelatedModels.push(relatedModel)
  }
}

CodePudding user response:

Use a type guard (TS Playground):

const relatedModels = parts
  .map(part => part.relatedModel)
  .filter((relatedModel): relatedModel is RelatedModel => !!relatedModel)
  • Related