Start an Astro project

Use TypeScript in Astro components

Type props and component code while remembering that the types disappear from runtime output.

8 minute lesson

~~~

Astro component scripts support TypeScript syntax inside the normal .astro extension.

---
interface Props {
  title: string
  published?: boolean
}

const { title, published = false } = Astro.props
---

<h2>{title}</h2>
{published && <p>Published</p>}

The interface checks component calls during development and build. It documents what the template expects.

Types disappear from runtime output. They do not validate a database response, form submission, environment value, or parsed JSON file.

If data crosses an untrusted boundary, validate it at runtime before treating it as the typed shape. Content collection schemas are one Astro-native example.

Keep types near the boundary they describe. A small Props interface in the component is often clearer than a distant shared type used once.

Pass a number to title and confirm the checker reports the call. Then parse invalid JSON and notice that a TypeScript annotation alone does not reject it.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →