Components and layouts

Type component props

Declare the component contract with a Props interface and provide defaults for optional values.

In the previous lesson, a component’s props were an informal agreement. Nothing stopped a parent from omitting a required value or passing the wrong type. TypeScript turns that agreement into a checked contract, and the mechanism is one interface with a reserved name.

Astro recognizes an interface named Props in the component script:

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

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

The name matters. Declare interface Props and Astro applies it to Astro.props and to every place the component is used. Now <Card featured="yes" /> is a type error, because a quoted attribute is a string and featured expects a boolean. Omitting title is a type error too. The interface documents the component at the point where people use it: hover a <Card> tag in the editor and you see exactly what it accepts.

Optional properties use ?, and their defaults belong in the destructuring statement. Keep the type and the default consistent:

---
interface Props {
  title: string
  count?: number
}

const { title, count = 0 } = Astro.props
---

If you declare count?: number but default it to '0', the annotation and the actual value disagree, and every consumer downstream inherits the confusion. The pattern above keeps the declaration and the fallback in one visible pair.

Where do the errors surface? In the editor as you type, and when you run astro check or a build that includes type checking. The mistake is expecting more than that. This is not runtime validation: the interface disappears from the compiled output. If props originate in a URL, form submission, CMS, or external API, validate that input before passing it to the component.

Think of Props as an internal programming contract, not a security boundary. It prevents accidental misuse by your code; it cannot make untrusted data truthful.

Add a Props interface to a component you already have, then deliberately break one call site with a wrong type. Confirm the editor flags the usage, not just the component file.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →