Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document use of Astro’s JSX types #1005

Merged
merged 3 commits into from
Jul 15, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion src/pages/en/guides/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,48 @@ export interface Props {
name: string;
greeting?: string;
}
const { greeting = 'Hello', name } = Astro.props as Props
const { greeting = 'Hello', name } = Astro.props as Props;
---
<h2>{greeting}, {name}!</h2>
```

### Built-in attribute types

Astro provides JSX type definitions to check your markup is using valid HTML attributes. You can use these types to help build component props. For example, if you were building a `<Link>` component, you could do the following to mirror the default HTML attributes in your component’s prop types.

```astro
---
export type Props = astroHTML.JSX.AnchorHTMLAttributes;
const { href, ...attrs } = Astro.props as Props;
---
<a {href} {...attrs}>
<slot />
</a>
```

It is also possible to extend the default JSX definitions to add non-standard attributes by redeclaring the `astroHTML.JSX` namespace in a `.d.ts` file.

```ts
// src/custom-attributes.d.ts

declare namespace astroHTML.JSX {
interface HTMLAttributes {
'data-count'?: number;
'data-label'?: string;
delucis marked this conversation as resolved.
Show resolved Hide resolved
}
}
```

:::note
`astroHTML` is injected globally inside `.astro` components. To use it in TypeScript files, use a [triple-slash directive](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html):

```ts
/// <reference types="astro/astro-jsx" />

type MyAttributes = astroHTML.JSX.ImgHTMLAttributes;
```
:::

## Type checking

To see type errors in your editor, please make sure that you have the [Astro VS Code extension](/en/editor-setup/) installed. Please note that the `astro start` and `astro build` commands will transpile the code with esbuild, but will not run any type checking. To prevent your code from building if it contains TypeScript errors, change your "build" script in `package.json` to the following:
Expand Down