Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript does not understand filter on undefined values in array of objects

Tags:

typescript

I struggle to make typescript understand that I'm already handling the undefined cases of one property (project) in this (shortened) example:

interface Entry {
    id: number
    project?: Project
    isPublished?: boolean
}

entries
     .filter(entry => !!entry.project)
     .map(entry => ({
           title: entry.project.title
     }))

(entries is an array of Entrys here) and the compiler complains on the line of entry.project.title on the project property that TS2532: Object is possibly 'undefined' even though I have the filter removing the undefined ones. The other optional property is still optional after the filtering, I thus cannot use Required interface :/

How can I make TS understand the property is definitely defined in the map function?

Thank you

-- Edit: added another optional property / clarification as response to a suggested answer that would make all properties required

like image 420
snoobpoob Avatar asked May 17 '26 12:05

snoobpoob


1 Answers

You need to define filter callback as a typeguard and use Required type util to make all interface props required:

type Project = {
  title: string
}

interface Entry {
  id: number
  project?: Project
}

type WithProject = Required<Entry>

declare const entries: Entry[]


entries
  .filter((entry): entry is WithProject => !!entry.project)
  .map(entry => ({
    title: entry.project.title
  }))

Playground

If you are interested in more type utils please see docs

like image 106
captain-yossarian Avatar answered May 20 '26 06:05

captain-yossarian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!