Types properties do not exist on slice variations

We're using Typescript in our Next.js project.

Slice item props that are unique to a slice variation are 'not found'.

We are declaring a slice props type as per below:

export type ContentFeaturesProps =
  SliceComponentProps<Content.ContentFeaturesSlice>

Within this slice we have a default variation and an "with icon" variation.

I can see that the type is generated and declared in prismicio.d.ts as:

type ContentFeaturesSliceVariation = ContentFeaturesSliceDefault | ContentFeaturesSliceContentFeaturesWithIcons;

In development / build, we get the below error:

Type error: Property 'icon' does not exist on type 'Simplify<ContentFeaturesSliceDefaultItem> | Simplify<ContentFeaturesSliceContentFeaturesWithIconsItem>'.
  Property 'icon' does not exist on type 'Simplify<ContentFeaturesSliceDefaultItem>'.

Should we be referencing a different type for the slice?

Javascript typedefs work fine, not typescript types.

/**
 * @typedef {import("@prismicio/client").Content.ContentFeaturesSlice} ContentFeaturesSlice
 * @typedef {import("@prismicio/react").SliceComponentProps<ContentFeaturesSlice>} ContentFeaturesProps
 * @param { ContentFeaturesProps }
 *

Please advise.

Work around for the time being is adding the below to the head of the file.

// @ts-nocheck

Keen for a solution on this.

Hello @james6

I have asked about this my dedicated team and they replied:

ContentFeaturesSliceVariation is a union of each variation, not an intersection, which means the type needs to be narrowed before using properties unique to a variation. Narrowing the type looks like this:

if (slice.variation === "ContentFeaturesWithIcons") {
  slice.primary.icon
  // ^ `primary.icon` is now defined
}

TypeScript requires this form of runtime checking to ensure the Slice contains a primary.icon property. If the Slice’s variation is “Default” instead of “ContentFeaturesWithIcons”, the primary.icon does not exist. I hope that helps!

Thanks,
Priyanka

2 Likes