Error in typing on a prismic application utilizing a ContentRelationshipField

I am facing a type error in my Prismic Next.js application that I am struggling to resolve. While the app functions properly, I keep encountering type errors like the following:

The property 'data' does not exist on the type 'ContentRelationshipField<"category">'. The property 'data' does not exist on the type 'EmptyLinkField<"Document>".'

My app includes articles associated with different categories. I am trying to fetch the color of the first category linked to these articles.

Below is the implementation of the Article component:

import React from "react";
import { PrismicLink, PrismicText } from "@prismicio/react";
import { PrismicNextImage } from "@prismicio/next";
import * as prismicH from "@prismicio/helpers";
import type { ArticleDocument, CategoryDocument } from "../../prismicio-types";
import { getExcerpt } from "../../lib/getExcerpt";
import { findFirstImage } from "../../lib/findFirstImage";
import { dateFormatter } from "../../lib/dateFormatter";
import { asapMedium } from "../../utils/font";

type ArticleProps = {
  article: ArticleDocument;
};

const Article: React.FC<ArticleProps> = ({ article }) => {
  const featuredImage =
    (prismicH.isFilled.image(article.data.featuredImage) &&
      article.data.featuredImage) ||
    findFirstImage(article.data.slices);
  const date = prismicH.asDate(
    article.data.publishDate || article.first_publication_date
  );
  const excerpt = getExcerpt(article.data.slices);
  const categoryColor = article.data.categories[0]?.category.data.color;
  const backgroundColor = categoryColor || "#ffffff";

  return (
    <li className="relative grid grid-cols-1 items-start gap-6 md:gap-8">
      <PrismicLink document={article} tabIndex={-1}>
        <div
          className="overlay-color z-10 md:block"
          key={article.id}
          style={{ backgroundColor }}
        ></div>
        <div className="bg-gray-100 aspect-h-3 aspect-w-4 relative">
          {prismicH.isFilled.image(featuredImage) && (
            <PrismicNextImage
              field={featuredImage}
              fill={true}
              width="0"
              height="0"
              sizes="100%"
              alt=""
              className="object-cover"
            />
          )}
        </div>
      </PrismicLink>
      <div
        className={`${asapMedium.className} overlay-text absolut-center-x absolute bottom-10 z-10 grid w-full grid-cols-1 justify-center gap-3 px-3 text-center align-top text-2xl uppercase drop-shadow-sm md:col-span-2`}
      >
        <h2 className="text-white">
          <PrismicLink document={article}>
            <PrismicText field={article.data.title} />
          </PrismicLink>
        </h2>
      </div>
    </li>
  );
};

export default Article;

The specific line causing the error is:

const categoryColor = article.data.categories[0]?.category.data.color;

Answer №1

To solve the issue, I devised a unique approach by crafting a bespoke type akin to the prismic type, tailored to fit my specific requirements.

const categoryColor = (
    article.data.categories[0]
      ?.category as CustomContentRelationshipFieldCategory
  )?.data?.color;

Although I am uncertain if this is the optimal solution, it does serve its purpose for now.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is jQuery noConflict really necessary?

I am a student who doesn't have much experience in the field of code development. I currently have my website up and running and I would like to add jetmenu to my template (that's all!). Here is the link to jetmenu: http://codecanyon.net/item/j ...

How can parameters be passed to a named function from a controller in AngularJS?

In my controller, I am working on breaking up my code into named functions to make it more readable. However, I am facing an issue where the scope and injected dependency are null in the parameterized named functions. How can I access these inside the name ...

Resolving TypeScript error: Property 'Error' does not exist on type 'Angular2 and Objects'

One of the models I am working with is called "opcionesautocomplete.model.ts" interface IOpcionesAutocomplete { opcionesStyle: OpcionStyle; pcionPropiedades: OpcionPropiedades; } export class OpcionesAutocomplete implements IOpcionesAutocomplet ...

Adjust columns sizes on ExtJS 6 dashboards in real-time

Is it possible to adjust the column widths within an Ext.dashboard.Dashboard once it has been displayed? The initial configuration sets the column widths as follows: columnWidths: [ 0.35, 0.40, 0.25 ] I would like to dynamically modify them ...

Retrieve information using AngularJS only when it is not yet defined

Currently, I am using $http in a controller to retrieve data and display it to the user. However, once the data is fetched for the first time, I do not want to fetch it again when moving between different tabs or controllers. My expertise lies in web dev ...

What is the best way to retrieve a value from async/await functions?

async function fetchNetworkStatus() { const network = await Network.getConnection(); setConnection(network.isConnected); console.log(connectionStatus); if (network.isConnected) { return true; } else { ...

What is the best way to layer four images in a 2x2 grid over another image using CSS as the background

I am attempting to place 4 images of the same size on a 5th image defined as the background. Currently, it looks like this: It works perfectly when the height is fixed, but in my case, the height may vary causing this issue: This problem isn't surp ...

What methods can Cypress use to validate content containing hyperlinks?

My current task is to develop an automation test that confirms the presence/display of content containing a hyperlink embedded within text. Please refer to the screenshot I have provided for better understanding, as it illustrates the specific content encl ...

What is the best way to effectively adjust the code structure in a Node.JS project?

[Summarized] Focus on the bold parts. Although I am relatively new to Node.JS, I have been able to successfully build some projects. However, I have come across a burning question that has left me frustrated after searching Google for answers without much ...

Manipulating SVG image color using JavaScript

Is there a way to change the colors of an svg image using Javascript? Perhaps by loading it as an object and accessing the color/image data? I would greatly appreciate any responses or tips on this matter! ...

Can you explain the purpose of the statement `var MyConstructor = function MyConstructor()`?

Can you explain the distinction between these two code snippets: var NodestrapGenerator = module.exports = function NodestrapGenerator() { yeoman.generators.Base.apply(this, arguments); // more code here }; and: var NodestrapGenerator = module.expor ...

Which superclass does ReadonlyArray extend from?

Looking at this TypeScript code snippet: const arr: ReadonlyArray<string> = [ "123", "234" ]; arr.push("345"); An error is thrown by the TS compiler: Property 'push' does not exist on type 'ReadonlyArray<string>&apo ...

Typescript custom react hook - toggling with useToggle

I developed a custom hook to toggle boolean values: import { useState } from 'react'; export function useToggle(initialValue: boolean) { const [value, setValue] = useState<boolean>(initialValue); const toggleValue = () => setValue ...

Async/Await mishap

Could someone please explain why the code below is printing a blank result? I was expecting it to print "done" since I thought the await keyword would make the program wait for the promise to be resolved. Appreciate any help provided! let message = &apos ...

The best approach to incorporating interactive animation in next.js

My vision is to develop a character creation application using next js. The app should empower users to customize the character using sliders and gender selection buttons. The ultimate goal is to have a 2D animated version of the character that dynamicall ...

Getting a ReferenceError while trying to use a MongoDB Collection variable in an external resolver file that had been imported through mergeResolvers

Here is a simplified example to illustrate the issue at hand. When using the resolver Query getAllUsers, the MongoDB Collection Users is not accessible in the external resolver file user.js. This results in the following error when executing the query: ...

Gathering information from various web pages simultaneously without the need to manually navigate through each page using a webdriver

I'm new to the world of web scraping and I've successfully developed a program that allows me to extract specific, dynamic data by utilizing the selenium web driver. My current project involves scraping data from a FAQ page in order to gather in ...

Unable to integrate third-party tools into your Vue JS project via CDN

Currently delving into Vue JS to enhance the interactivity of my django application, I am opting for the route of integrating Vue JS as components within my templates rather than going down the path of a Single Page Application (SPA). It's almost like ...

ReactPlayer allows for the simultaneous playback of two files

I am trying to simultaneously play two files in reactjs using ReactPlayer. The first file is a video music clip that includes human voice audio, while the second file is music only without the human voice. My issue is that when I run the code provided, ei ...

Utilizing the zIndex property on a map label does not produce any impact when combined with a GeoJSON layer

Utilizing the Google map label tool, I am trying to showcase certain property from GeoJSON data on a GeoJSON layer. However, the issue arises as the layer has a dark color and the label is appearing blurry behind the GeoJSON data layer. Despite attempting ...