From 028b76ba6bafb3ae3c0ab47a2ae382fd622fc072 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 13 Oct 2024 17:03:25 -0500 Subject: [PATCH] Add Generate Types For A Content Collection as an Astro TIL --- README.md | 3 +- ...generate-types-for-a-content-collection.md | 56 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 astro/generate-types-for-a-content-collection.md diff --git a/README.md b/README.md index aa8dcc0..7ba7bc6 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1465 TILs and counting..._ +_1466 TILs and counting..._ --- @@ -101,6 +101,7 @@ _1465 TILs and counting..._ ### Astro +- [Generate Types For A Content Collection](astro/generate-types-for-a-content-collection.md) - [Markdown Files Are Of Type MarkdownInstance](astro/markdown-files-are-of-type-markdown-instance.md) ### Brew diff --git a/astro/generate-types-for-a-content-collection.md b/astro/generate-types-for-a-content-collection.md new file mode 100644 index 0000000..4ee81be --- /dev/null +++ b/astro/generate-types-for-a-content-collection.md @@ -0,0 +1,56 @@ +# Generate Types For A Content Collection + +Let's say I'm using Astro to publish posts via markdown. One of the best ways +to do that is as a _Content Collection_. The posts will live in `src/content` +probably under a `posts` directory. Plus a config file will define the +collection and specify validations for the frontmatter. + +```typescript +// src/content/config.ts +import { defineCollection, z } from 'astro:content'; + +const postsCollection = defineCollection({ + schema: z.object({ + title: z.string(), + description: z.string(), + tags: z.array(z.string()) + }) +}); + +export const collections = { + 'posts': postsCollection, +}; +``` + +When I first add this to my project and get the collection, it won't know what +the types are. + +```astro +--- +import { getCollection } from "astro:content"; + +export async function getStaticPaths() { + const blogEntries = await getCollection("posts"); + // ^^^ any + + return blogEntries.map((entry) => ({ + params: { slug: entry.slug }, + props: { entry }, + })); +} +--- +``` + +I can tell Astro to generate a fresh set of types for things like content +collections by running the [`astro sync` +command](https://docs.astro.build/en/reference/cli-reference/#astro-sync). + +```bash +$ npm run astro sync +``` + +This updates auto-generated files under the `.astro` directory which get pulled +in to your project's `env.d.ts` file. + +All of these types will also be synced anytime I run `astro dev`, `astro +build`, or `astro check`.