All questions

How do I get the content from a slot properly typed in TypeScript?

Asked by mira_ts on

Mmira_ts

wiring up content fetching and the content coming back is basically unknown, so I get no autocomplete and no safety on the fields. Right now I am casting it to a hand-written interface, which defeats the point because nothing keeps that interface in sync with the actual schema.

I run strict everywhere and I do not want any anywhere near this. Is there a supported way to get a slot's content strongly typed from the slot id, rather than me maintaining a parallel type by hand

Was this helpful?

2 answers

PRPriya RamanAccepted answer

There is, and you can drop the hand-written interface entirely.

The package exports a SlotContent type keyed by slot id, so SlotContent<'home-hero@1'> is the exact shape for that slot. But you do not even have to reach for it directly in most cases. The CLI generates a slots.d.ts declaration file, and once that is present, useContent and fetchContent infer the content type straight from the slot id literal you pass:

// content is fully typed, no castconst {content} = await fetchContent('home-hero@1');

The literal 'home-hero@1' is what drives the inference, so autocomplete and field safety come for free. If you ever need the type on its own, that is what SlotContent<'home-hero@1'> is for.

One thing on the id itself: you can pin a version like 'home-hero@2'. Leaving the version off means latest, which infers fine today but lets a published schema change move under you later. See A content publish broke my build because the slot type changed for why pinning is worth it.

Was this helpful?
Ddooley

Adding one thing since it bit us: commit slots.d.ts to the repo. Generating it at build time needs an API fetch, so if you leave it out, CI has no declarations and every SlotContent<...> fails to resolve on the runner even though it compiles locally. There is a whole thread on getting that deterministic in How should croct.json5 version specifiers and slots.d.ts play with CI builds? if you are setting up a pipeline.

Was this helpful?
Mmira_ts

deleted my fake interface, the inference from the slot id just works. committed the file too so it does not blow up in CI later. thanks both

Still have questions?