TypeScript errors with Content Relationship fields

Hi there,

This is expected TypeScript behavior with Prismic content relationships. By default, TypeScript only knows that a content relationship is a link field, it does not automatically know which linked fields were fetched via fetchLinks or graphQuery. (Prismic People)

The recommended approach is to use a type predicate/helper function to narrow the type before accessing .data. This is especially useful for Slice fields and nested relationships. (Prismic People)

For example:

import * as prismicH from "@prismicio/helpers";
import * as prismicT from "@prismicio/types";
import { Content } from "@prismicio/client";

const hasParentData = <
  TContentRelationshipField extends prismicT.ContentRelationshipField
>(
  field: TContentRelationshipField
): field is TContentRelationshipField & {
  data: {
    parent: Pick<Content.PageDocument["data"], "title">;
  };
} => {
  return (
    prismicH.isFilled.contentRelationship(field) &&
    typeof field.data === "object" &&
    field.data !== null &&
    "parent" in field.data
  );
};

Then:

if (hasParentData(slice.primary.link)) {
  slice.primary.link.data.parent.title;
}

A few important notes:

  • isFilled.contentRelationship() only checks whether the relationship itself exists.

  • It does not tell TypeScript which linked fields were fetched.

  • The linked fields must also be included in your query via fetchLinks or graphQuery. (Prismic People)

We have a few community threads covering similar cases here:

Hope that helps clarify things a bit :slightly_smiling_face: