All questions

Best way to get typed slot content in a TypeScript Hydrogen project?

Asked by Priyanka Menon on

PMPriyanka Menon

Our Hydrogen storefront is strict TypeScript, no implicit any, and I would like slot content to be typed end to end rather than casting the fetch result to any in each loader. Casting works but it defeats the point of running strict.

What is the intended setup here? I would rather adopt the canonical approach than hand-roll interfaces that drift from what the slot actually returns.

Was this helpful?

2 answers

MPMarcos PassosAccepted answer

There is a first-class path for this, no hand-rolled interfaces needed. The package exports a content type keyed by slot id and version, so you can write SlotContent<'home-hero@1'> and get the exact shape that slot returns at that version. That is the type to reach for instead of casting to any.

What makes it ergonomic is that the CLI generates a slots.d.ts with the types for all of your configured slots, so those keyed lookups resolve without you declaring anything. The type generation reference covers how that file is produced, and the Hydrogen content rendering guide shows the typed fetch in a loader.

One habit that keeps it honest: pin the version in the type the same way you pin it in the fetch. SlotContent<'home-hero@1'> alongside fetchContent('home-hero@1') means the type you code against is the version you actually resolve, so a schema change on a later version cannot silently diverge from your components.

Was this helpful?
Ssam_ck

For anyone else setting this up: commit the generated slots.d.ts to the repo. If it is checked in, CI and your build resolve the types straight from the file with no API fetch at build time, and everyone on the team gets the same types without running the generator locally first. We learned that after a fresh clone failed to typecheck because the file was gitignored.

Was this helpful?
Still have questions?