Type-Safe Template Rendering
At Accella, we use Astro components for page rendering. Astro components, like React’s JSX or Vue’s SFC, allow you to write type-safe components using TypeScript.
This type safety helps improve code quality compared to using other server-side template engines (such as EJS or Pug for JavaScript, ERB for Ruby, or Jinja2 for Python).
Type Checking for Components
TypeScript’s type checker will throw an error if you reference non-existent variables or methods.
---const name = "Accella";---<p>{name}</p> <!-- Outputs <p>Accella</p> --><p>{foo}</p> <!-- Error: Cannot find name 'foo'. -->
---interface User { name: string; greet(): string;}const user: User = { name: "Alice", greet() { return `Hello, ${this.name}!`; }}---<p>{user.name}</p> <!-- Outputs <p>Alice</p> --><p>{user.foo}</p> <!-- Error: Property 'foo' does not exist on type 'User'. -->
<p>{user.greet()}</p> <!-- Outputs <p>Hello, Alice!</p> --><p>{user.bar()}</p> <!-- Error: Property 'bar' does not exist on type 'User'. -->
Component Props Types
Astro components can receive props just like React’s JSX. By specifying the types of props, you can catch errors when the props are used incorrectly.
---interface Props { name: string;}const { name } = Astro.props;---<h1>Hello, {name}!</h1>
---import Hello from "src/components/Hello.astro";---<Hello name="Alice" /> <!-- Outputs <h1>Hello, Alice!</h1> --><Hello name={123} /> <!-- Error: Type 'number' is not assignable to type 'string'. --><Hello foo="Alice" /> <!-- Error: Type '{ foo: string; }' is not assignable to type 'Props'. -->
Related Links
- Template expressions reference (Astro Docs)
- Component Props (Astro Docs)