> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/withastro/astro/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript Configuration

> Configure TypeScript in your Astro project for type safety and better developer experience

Astro provides first-class TypeScript support out of the box. This guide covers how to configure TypeScript in your Astro project for optimal type safety and developer experience.

## Quick Start

Astro includes TypeScript support by default. No installation required - just start using `.ts` and `.astro` files.

<Steps>
  <Step title="Generate types">
    Run `astro sync` to generate TypeScript types for your content collections and integrations:

    ```bash theme={null}
    npx astro sync
    ```
  </Step>

  <Step title="Create tsconfig.json">
    Add a `tsconfig.json` file to your project root:

    ```json title="tsconfig.json" theme={null}
    {
      "extends": "astro/tsconfigs/strict"
    }
    ```
  </Step>

  <Step title="Start developing">
    Use TypeScript in your `.astro`, `.ts`, and `.tsx` files:

    ```astro title="src/pages/index.astro" theme={null}
    ---
    interface Props {
      title: string;
      count: number;
    }

    const { title, count } = Astro.props;
    ---
    <h1>{title}</h1>
    <p>Count: {count}</p>
    ```
  </Step>
</Steps>

## TypeScript Configuration

### Using Astro's Presets

Astro provides three TypeScript presets to choose from:

<Tabs>
  <Tab title="strict (recommended)">
    The strictest TypeScript settings. Recommended for most projects.

    ```json title="tsconfig.json" theme={null}
    {
      "extends": "astro/tsconfigs/strict"
    }
    ```

    Enables:

    * `strict: true`
    * `strictNullChecks: true`
    * `noUnusedLocals: true`
    * `noUnusedParameters: true`
    * And more strict checks
  </Tab>

  <Tab title="base">
    Balanced settings for most TypeScript users.

    ```json title="tsconfig.json" theme={null}
    {
      "extends": "astro/tsconfigs/base"
    }
    ```

    Enables essential TypeScript features without the strictest checks.
  </Tab>

  <Tab title="strictest">
    Maximum strictness for teams that want every possible check.

    ```json title="tsconfig.json" theme={null}
    {
      "extends": "astro/tsconfigs/strictest"
    }
    ```

    Includes all checks from `strict` plus additional pedantic rules.
  </Tab>
</Tabs>

### Custom TypeScript Configuration

You can extend Astro's presets with your own settings:

```json title="tsconfig.json" theme={null}
{
  "extends": "astro/tsconfigs/strict",
  "include": [".astro/types.d.ts", "**/*"],
  "exclude": ["dist"],
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/components/*"],
      "@layouts/*": ["src/layouts/*"]
    },
    "strictPropertyInitialization": false
  }
}
```

<Accordion title="Common compilerOptions">
  * **`baseUrl`**: Base directory for resolving non-relative module names
  * **`paths`**: Path mapping for module resolution (like aliases)
  * **`target`**: ECMAScript target version (default: `ES2022`)
  * **`module`**: Module code generation (default: `ESNext`)
  * **`lib`**: Library files to include (default: `["ES2022"]`)
  * **`jsx`**: JSX code generation (Astro handles this automatically)
  * **`resolveJsonModule`**: Allow importing `.json` files
  * **`allowJs`**: Allow JavaScript files in your project
</Accordion>

### Include and Exclude Patterns

Control which files TypeScript processes:

```json title="tsconfig.json" theme={null}
{
  "extends": "astro/tsconfigs/strict",
  "include": [
    ".astro/types.d.ts",
    "**/*"
  ],
  "exclude": [
    "dist",
    "node_modules",
    ".astro"
  ]
}
```

<Note>
  Always include `.astro/types.d.ts` - this file contains generated types for content collections and integrations.
</Note>

## Type Checking

Astro doesn't type-check during development for performance. Use these methods to check types:

### During Development

<Tabs>
  <Tab title="VSCode">
    Install the [Astro VSCode extension](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode) for inline type checking.

    Configure your editor to show TypeScript errors:

    ```json title=".vscode/settings.json" theme={null}
    {
      "astro.typescript.enabled": true
    }
    ```
  </Tab>

  <Tab title="CLI">
    Run type checking manually:

    ```bash theme={null}
    npx astro check
    ```

    Or in watch mode:

    ```bash theme={null}
    npx astro check --watch
    ```
  </Tab>
</Tabs>

### In CI/CD

Add type checking to your build process:

```json title="package.json" theme={null}
{
  "scripts": {
    "build": "astro check && astro build",
    "check": "astro check"
  }
}
```

<CodeGroup>
  ```yaml title="GitHub Actions" theme={null}
  - name: Type check
    run: npm run check
  ```

  ```yaml title="GitLab CI" theme={null}
  typecheck:
    script:
      - npm run check
  ```
</CodeGroup>

## Generated Types

Astro automatically generates types for your project:

### Content Collections

Types are generated for content collections in `.astro/types.d.ts`:

```ts title="src/content/config.ts" theme={null}
import { defineCollection, z } from 'astro:content';

const blog = defineCollection({
  type: 'content',
  schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.date(),
  }),
});

export const collections = { blog };
```

Use generated types in your code:

```astro title="src/pages/blog/[...slug].astro" theme={null}
---
import { getCollection, type CollectionEntry } from 'astro:content';

type BlogPost = CollectionEntry<'blog'>;

const posts: BlogPost[] = await getCollection('blog');
---
```

### Integration Types

Integrations can add their own type definitions. Run `astro sync` to generate them:

```bash theme={null}
npx astro sync
```

<Tip>
  Add `astro sync` to your `prepare` script to run it automatically on `npm install`:

  ```json title="package.json" theme={null}
  {
    "scripts": {
      "prepare": "astro sync"
    }
  }
  ```
</Tip>

## Type Safety in Astro Files

### Component Props

Define types for component props:

```astro title="src/components/Card.astro" theme={null}
---
interface Props {
  title: string;
  description?: string;
  href: string;
}

const { title, description, href } = Astro.props;
---
<a href={href}>
  <h3>{title}</h3>
  {description && <p>{description}</p>}
</a>
```

### Frontmatter Type Assertions

Use type assertions for complex data:

```astro title="src/pages/about.astro" theme={null}
---
import type { Author } from '../types';

const author: Author = {
  name: 'Jane Doe',
  email: 'jane@example.com',
  bio: 'Developer and writer'
};
---
```

### Global Types

Define global types in a `.d.ts` file:

```ts title="src/types/global.d.ts" theme={null}
declare module '*.svg' {
  const content: string;
  export default content;
}

interface Window {
  analytics?: any;
}
```

## Import Aliases

Configure path aliases for cleaner imports:

<Steps>
  <Step title="Configure tsconfig.json">
    ```json title="tsconfig.json" theme={null}
    {
      "extends": "astro/tsconfigs/strict",
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@components/*": ["src/components/*"],
          "@layouts/*": ["src/layouts/*"],
          "@lib/*": ["src/lib/*"]
        }
      }
    }
    ```
  </Step>

  <Step title="Use aliases in your code">
    ```astro title="src/pages/index.astro" theme={null}
    ---
    import Layout from '@layouts/Layout.astro';
    import Card from '@components/Card.astro';
    import { formatDate } from '@lib/utils';
    ---
    ```
  </Step>
</Steps>

<Note>
  Astro provides a default `@/*` alias that maps to `src/*`. You can use this without additional configuration.
</Note>

## Framework-Specific TypeScript

### React

```tsx title="src/components/Counter.tsx" theme={null}
import { useState, type FC } from 'react';

interface CounterProps {
  initial?: number;
}

const Counter: FC<CounterProps> = ({ initial = 0 }) => {
  const [count, setCount] = useState(initial);
  
  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
};

export default Counter;
```

### Vue

```vue title="src/components/Counter.vue" theme={null}
<script setup lang="ts">
interface Props {
  initial?: number;
}

const props = withDefaults(defineProps<Props>(), {
  initial: 0
});

const count = ref(props.initial);
</script>
```

### Svelte

```svelte title="src/components/Counter.svelte" theme={null}
<script lang="ts">
  export let initial: number = 0;
  let count = initial;
</script>

<button on:click={() => count++}>
  Count: {count}
</button>
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="Types not updating">
    Run `astro sync` to regenerate types:

    ```bash theme={null}
    npx astro sync
    ```

    If issues persist, delete `.astro/types.d.ts` and run sync again.
  </Accordion>

  <Accordion title="Cannot find module errors">
    Ensure `.astro/types.d.ts` is included in your `tsconfig.json`:

    ```json title="tsconfig.json" theme={null}
    {
      "include": [".astro/types.d.ts", "**/*"]
    }
    ```

    Restart your TypeScript server in your editor.
  </Accordion>

  <Accordion title="Path aliases not working">
    Verify your `tsconfig.json` has both `baseUrl` and `paths` configured:

    ```json title="tsconfig.json" theme={null}
    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@components/*": ["src/components/*"]
        }
      }
    }
    ```
  </Accordion>

  <Accordion title="Strict mode errors">
    If you're getting too many errors with strict mode, start with the `base` preset:

    ```json title="tsconfig.json" theme={null}
    {
      "extends": "astro/tsconfigs/base"
    }
    ```

    Gradually enable strict options as you fix issues.
  </Accordion>
</AccordionGroup>

## Best Practices

<CardGroup cols={2}>
  <Card title="Use strict mode" icon="shield-check">
    Enable strict TypeScript checks to catch errors early
  </Card>

  <Card title="Run astro sync" icon="arrows-rotate">
    Keep generated types up-to-date, especially after schema changes
  </Card>

  <Card title="Type component props" icon="cube">
    Always define interfaces for component props
  </Card>

  <Card title="Check in CI/CD" icon="circle-check">
    Add `astro check` to your CI pipeline
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Content Collections" icon="folder" href="/concepts/content-collections">
    Learn about type-safe content collections
  </Card>

  <Card title="Astro Config" icon="gear" href="/config/astro-config">
    Configure your Astro project
  </Card>

  <Card title="Environment Variables" icon="key" href="/features/env-variables">
    Type-safe environment variables
  </Card>

  <Card title="Editor Setup" icon="code" href="/installation">
    Set up your editor for Astro
  </Card>
</CardGroup>
