Skip to content

Commit

Permalink
Document use of Astro’s JSX types (withastro#1005)
Browse files Browse the repository at this point in the history
* Document use of Astro’s JSX types

Closes withastro#984

* Use new element-specific interface

Co-authored-by: Erika <[email protected]>

* Add note about `astroHTML` in `.ts` files

Co-authored-by: Erika <[email protected]>
  • Loading branch information
delucis and Princesseuh authored Jul 15, 2022
1 parent c39186d commit a1ecd87
Showing 1 changed file with 38 additions and 1 deletion.
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;
}
}
```

:::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

0 comments on commit a1ecd87

Please sign in to comment.