Skip to content

Commit c93b44b

Browse files
Fix TypeScript errors in "Add content to your site" code snippets (#14091)
Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com>
1 parent 0f46881 commit c93b44b

3 files changed

Lines changed: 77 additions & 47 deletions

File tree

src/content/docs/en/guides/content-collections.mdx

Lines changed: 63 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -208,13 +208,16 @@ Your blog post content here.
208208
You can also pass options to the `glob()` loader's [`generateID()` helper function](/en/reference/content-loader-reference/#generateid) when you define your build-time collection to adjust how `id`s are generated. For example, you may wish to revert the default behavior of converting uppercase letters to lowercase for each collection entry:
209209

210210
```js title="src/content.config.ts"
211+
import { glob } from "astro/loaders";
212+
import { defineCollection } from "astro:content";
213+
211214
const authors = defineCollection({
212215
/* Retrieve all JSON files in your authors directory while retaining
213216
* uppercase letters in the ID. */
214217
loader: glob({
215-
pattern: '**/*.json',
218+
pattern: "**/*.json",
216219
base: "./src/data/authors",
217-
generateId: ({ entry }) => entry.replace(/\.json$/, ''),
220+
generateId: ({ entry }) => entry.replace(/\.json$/, ""),
218221
}),
219222
});
220223
```
@@ -224,8 +227,8 @@ const authors = defineCollection({
224227
The [`file()` loader](/en/reference/content-loader-reference/#file-loader) fetches multiple entries from a single local file defined in your collection. The `file()` loader will automatically detect and parse (based on the file extension) a single array of objects from JSON and YAML files, and will treat each top-level table as an independent entry in TOML files.
225228

226229
```ts title="src/content.config.ts" {5}
227-
import { defineCollection } from 'astro:content';
228-
import { file } from 'astro/loaders';
230+
import { defineCollection } from "astro:content";
231+
import { file } from "astro/loaders";
229232

230233
const dogs = defineCollection({
231234
loader: file("src/data/dogs.json"),
@@ -301,8 +304,8 @@ You can [build a custom loader](/en/reference/content-loader-reference/#building
301304
Then you can import and define your custom loader in your collections config, passing any required values:
302305

303306
```ts title="src/content.config.ts"
304-
import { defineCollection } from 'astro:content';
305-
import { myLoader } from './loader.ts';
307+
import { defineCollection } from "astro:content";
308+
import { myLoader } from "./loader.ts";
306309

307310
const blog = defineCollection({
308311
loader: myLoader({
@@ -335,9 +338,9 @@ In order for Astro to recognize a new or updated schema, you may need to restart
335338
Providing a `schema` is optional, but highly recommended! If you choose to use a schema, then every frontmatter or data property of your collection entries must be defined using a [Zod data type](/en/reference/modules/astro-zod/#common-data-type-validators):
336339

337340
```ts title="src/content.config.ts" {7-12,16-20}
338-
import { defineCollection } from 'astro:content';
339-
import { z } from 'astro/zod';
340-
import { glob, file } from 'astro/loaders';
341+
import { defineCollection } from "astro:content";
342+
import { z } from "astro/zod";
343+
import { glob, file } from "astro/loaders";
341344

342345
const blog = defineCollection({
343346
loader: glob({ pattern: "**/*.md", base: "./src/data/blog" }),
@@ -346,7 +349,7 @@ const blog = defineCollection({
346349
description: z.string(),
347350
pubDate: z.coerce.date(),
348351
updatedDate: z.coerce.date().optional(),
349-
})
352+
}),
350353
});
351354
const dogs = defineCollection({
352355
loader: file("src/data/dogs.json"),
@@ -381,27 +384,27 @@ With the [`reference()` function](/en/reference/modules/astro-content/#reference
381384
A common example is a blog post that references reusable author profiles stored as JSON, or related post URLs stored in the same collection:
382385

383386
```ts title="src/content.config.ts"
384-
import { defineCollection, reference } from 'astro:content';
385-
import { glob } from 'astro/loaders';
386-
import { z } from 'astro/zod';
387+
import { defineCollection, reference } from "astro:content";
388+
import { glob } from "astro/loaders";
389+
import { z } from "astro/zod";
387390

388391
const blog = defineCollection({
389-
loader: glob({ base: './src/content/blog', pattern: '**/*.{md,mdx}' }),
392+
loader: glob({ base: "./src/content/blog", pattern: "**/*.{md,mdx}" }),
390393
schema: z.object({
391394
title: z.string(),
392395
// Reference a single author from the `authors` collection by `id`
393-
author: reference('authors'),
396+
author: reference("authors"),
394397
// Reference an array of related posts from the `blog` collection by `id`
395-
relatedPosts: z.array(reference('blog')),
396-
})
398+
relatedPosts: z.array(reference("blog")),
399+
}),
397400
});
398401

399402
const authors = defineCollection({
400-
loader: glob({ pattern: '**/*.json', base: "./src/data/authors" }),
403+
loader: glob({ pattern: "**/*.json", base: "./src/data/authors" }),
401404
schema: z.object({
402405
name: z.string(),
403406
portfolio: z.url(),
404-
})
407+
}),
405408
});
406409

407410
export const collections = { blog, authors };
@@ -484,14 +487,19 @@ Once queried, you can render Markdown and MDX entries to HTML using the [`render
484487

485488
```astro title="src/pages/blog/post-1.astro" {2,6,10}
486489
---
487-
import { getEntry, render } from 'astro:content';
490+
import { getEntry, render } from "astro:content";
488491
489-
const entry = await getEntry('blog', 'post-1');
492+
const entry = await getEntry("blog", "post-1");
493+
494+
if (!entry) {
495+
throw new Error("Entry not found");
496+
}
490497
491498
const { Content } = await render(entry);
492499
---
500+
493501
<h1>{entry.data.title}</h1>
494-
<p>Published on: {entry.data.published.toDateString()}</p>
502+
<p>Published on: {entry.data.pubDate.toDateString()}</p>
495503
<Content />
496504
```
497505

@@ -564,10 +572,15 @@ Then, you can use the `getEntry()` function again (or `getEntries()` to retrieve
564572

565573
```astro title="src/pages/blog/adventures-in-space.astro"
566574
---
567-
import { getEntry, getEntries } from 'astro:content';
575+
import { getEntry, getEntries } from "astro:content";
568576
569577
// First, query a blog post
570-
const blogPost = await getEntry('blog', 'Adventures in Space');
578+
const blogPost = await getEntry("blog", "Adventures in Space");
579+
580+
// If the blog post doesn't exist, throw an error
581+
if (!blogPost) {
582+
throw new Error("Blog post not found");
583+
}
571584
572585
// Retrieve a single reference item: the blog post's author
573586
// Equivalent to querying `{collection: "authors", id: "ben-holmes"}`
@@ -584,9 +597,7 @@ const relatedPosts = await getEntries(blogPost.data.relatedPosts);
584597
<!-- ... -->
585598
586599
<h2>You might also like:</h2>
587-
{relatedPosts.map(post => (
588-
<a href={post.id}>{post.data.title}</a>
589-
))}
600+
{relatedPosts.map((post) => <a href={post.id}>{post.data.title}</a>)}
590601
```
591602

592603
## Generating Routes from Content
@@ -797,16 +808,20 @@ You can use these functions to access your live data, passing the name of the co
797808
---
798809
export const prerender = false; // Not needed in 'server' mode
799810
800-
import { getLiveCollection, getLiveEntry } from 'astro:content';
811+
import { getLiveCollection, getLiveEntry } from "astro:content";
812+
813+
if (!Astro.params.slug) {
814+
return Astro.redirect('/404');
815+
}
801816
802817
// Use loader-specific filters
803-
const { entries: draftArticles } = await getLiveCollection('articles', {
804-
status: 'draft',
805-
author: 'john-doe',
818+
const { entries: draftArticles } = await getLiveCollection("articles", {
819+
status: "draft",
820+
author: "john-doe",
806821
});
807822
808823
// Get a specific product by ID
809-
const { entry: product } = await getLiveEntry('products', Astro.params.slug);
824+
const { entry: product } = await getLiveEntry("products", Astro.params.slug);
810825
---
811826
```
812827

@@ -820,10 +835,14 @@ You also have access to any [error returned by the live loader](/en/reference/co
820835
---
821836
export const prerender = false; // Not needed in 'server' mode
822837
823-
import { getLiveEntry, render } from 'astro:content';
824-
const { entry, error } = await getLiveEntry('articles', Astro.params.id);
825-
if (error) {
826-
return Astro.rewrite('/404');
838+
if (!Astro.params.id) {
839+
return Astro.redirect("/404");
840+
}
841+
842+
import { getLiveEntry, render } from "astro:content";
843+
const { entry, error } = await getLiveEntry("articles", Astro.params.id);
844+
if (!entry || error) {
845+
return Astro.rewrite("/404");
827846
}
828847
829848
const { Content } = await render(entry);
@@ -851,18 +870,22 @@ You can use `instanceof` to check the type of an error at runtime:
851870
---
852871
export const prerender = false; // Not needed in 'server' mode
853872
854-
import { LiveEntryNotFoundError } from 'astro/content/runtime';
855-
import { getLiveEntry } from 'astro:content';
873+
import { LiveEntryNotFoundError } from "astro/content/runtime";
874+
import { getLiveEntry } from "astro:content";
875+
876+
if (!Astro.params.id) {
877+
return Astro.redirect("/404");
878+
}
856879
857-
const { entry, error } = await getLiveEntry('products', Astro.params.id);
880+
const { entry, error } = await getLiveEntry("products", Astro.params.id);
858881
859882
if (error) {
860883
if (error instanceof LiveEntryNotFoundError) {
861884
console.error(`Product not found: ${error.message}`);
862885
Astro.response.status = 404;
863886
} else {
864887
console.error(`Error loading product: ${error.message}`);
865-
return Astro.redirect('/500');
888+
return Astro.redirect("/500");
866889
}
867890
}
868891
---

src/content/docs/en/guides/images.mdx

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -468,11 +468,12 @@ For example, you could create a component for your blog post images that receive
468468

469469
```astro title="src/components/BlogPostImage.astro"
470470
---
471-
import { Image } from 'astro:assets';
471+
import { Image } from "astro:assets";
472472
473-
const { src, ...attrs } = Astro.props;
473+
const { alt, src, ...attrs } = Astro.props;
474474
---
475-
<Image src={src} {...attrs} />
475+
476+
<Image alt={alt} src={src} {...attrs} />
476477
477478
<style>
478479
img {
@@ -649,7 +650,7 @@ const optimizedBackground = await getImage({ src: myBackground, format: "avif" }
649650
<div id="background" data-src={optimizedBackground.src}></div>
650651
651652
<script>
652-
const src = document.getElementById("background").dataset.src;
653+
const src = document.getElementById("background")?.dataset.src;
653654
// use src client-side as needed
654655
</script>
655656
```

src/content/docs/en/guides/markdown-content.mdx

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,9 @@ Here is my _great_ post!
5050

5151
```astro title="src/pages/my-posts.astro"
5252
---
53-
import * as greatPost from './posts/great-post.md';
53+
import * as greatPost from "./posts/great-post.md";
5454
const compiled = await greatPost.compiledContent();
55-
const posts = Object.values(import.meta.glob('./posts/*.md', { eager: true }));
55+
const posts = Object.values(import.meta.glob("./posts/*.md", { eager: true }));
5656
---
5757
5858
<p>{greatPost.frontmatter.title}</p>
@@ -62,7 +62,13 @@ const posts = Object.values(import.meta.glob('./posts/*.md', { eager: true }));
6262
6363
<p>Post Archive:</p>
6464
<ul>
65-
{posts.map(post => <li><a href={post.url}>{post.frontmatter.title}</a></li>)}
65+
{
66+
posts.map((post: any) => (
67+
<li>
68+
<a href={post.url}>{post.frontmatter.title}</a>
69+
</li>
70+
))
71+
}
6672
</ul>
6773
```
6874

0 commit comments

Comments
 (0)