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:
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
}
}