#Can I get a Typescript type for a content collection schema?

4 messages · Page 1 of 1 (latest)

minor cloak
#

I want to use multiple content collections with the same schema. I want to decouple my components from a specific content collection. How can I use a Typescript type in my components and layouts representing the content collection schema?

quasi sableBOT
#

Hi @minor cloak. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can get a TypeScript type for a content collection schema in Astro. You can use the CollectionEntry utility to correctly type your component's props using TypeScript. This utility takes a string argument that matches the name of your collection schema, and will inherit all of the properties of that collection’s schema.

Here is an example of how you can use it in your Astro component:

---
import type { CollectionEntry } from 'astro:content';
interface Props { 
  post: CollectionEntry<'blog'>
}

// `post` will match your 'blog' collection schema type
const { post } = Astro.props;
---

In the above example, post will match your 'blog' collection schema type. This way, you can decouple your components from a specific content collection and use the same schema across multiple collections.

For more details, you can refer to the Astro documentation (https://docs.astro.build/en/guides/content-collections#passing-content-as-props).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@minor cloak kapa.ai is still learning and improving, please let us know how it did by reacting below