How do you properly type ``Relational`` fields?

I am trying to type a Relational field but I keep getting an error saying data does not exist on the object I am retrieving. It only worked when I used a PrismicDocument but I understand that you can't use a PrismicDocument so I utilized the direct object typing and it stopped working. Screenshots below:

Type Im trying to use
Screen Shot 2022-05-06 at 9.07.02 AM

Relational typing attempt

Error

Hello @developer4, thanks for reaching out. I'll ask the team and come back when I have more information.

Thanks

I have a response from the team:

This is happening most likely because the code is not handling the case where the link field is empty. If it is empty, then the data property won’t exist (since it isn’t linked to a document).

To handle this correctly (with correct types), the isFilled helpers from @prismicio/helpers can be used:

import * as prismicH from '@prismicio/helpers'

if (prismicH.isFilled.contentRelationship(field)) {
  // Access the page_title field
  // Note that the field is still marked as nullable (see the ?. syntax).
  // This is to handle the case where a `fetchLinks` or `graphQuery` option was not passed to the query.
  field.data?.page_title

  // Alternatively, an if block could narrow the type:
  if (field.data) {
    field.data.page_title
  }
}
1 Like