Astro JS - TypeScript



Astro TypeScript Support

TypeScript is a superset of JavaScript that compiles code into plain JavaScript. It is a statically typed language that supports object-oriented programming. Using TypeScript, you can prevent errors at runtime by defining the shapes of objects and components in your code.

Astro comes with inbuilt support for TypeScript. You can use '.ts' or '.tsx' files to write your Astro components and pages in TypeScript. Astro will compile these files to JavaScript. Also, Astro provides a TypeScript configuration file that you can use to configure TypeScript for your Astro project.

TypeScript Configuration File

The TypeScript configuration file is used to configure TypeScript for your Astro project. Every Astro starter projects include a 'tsconfig.json' file by default. Even if you don’t write TypeScript code, this file is important so that tools like Astro and VS Code know how to understand your project. Some features (like npm package imports) aren’t fully supported in the editor without a 'tsconfig.json' file. If you install Astro manually, be sure to create this file yourself.

Example

The configuration file in the below section, sets strict compiler options for TypeScript in an Astro project.

{
  "extends": "astro/tsconfigs/strictest",
  "compilerOptions": {
    "strict": true,
    "moduleResolution": "node",
    "allowJs": true,
    "jsx": "preserve"
  }
}

Templates of Config File

In Astro there are three extensible templates for typescript configuration:

  • base: The base template is used to enable support for modern JavaScript features.
  • strict: The strict template is used to enable strict type checking and modern JavaScript features.
  • strictest: The strictest template is used to enable the strictest type checking and modern JavaScript features.

Example

The configuration file in the below section, extends the 'base' template for TypeScript in an Astro project.

{
  "extends": "astro/tsconfigs/base"
}

Astro TypeScript Plugin

The Astro TypeScript plugin is used to enable TypeScript support in Astro. This will be installed automatically when you install Astro vscode extension. You can install it separately if you are not using vscode extension. This plugin runs only in the editor. When running tsc in the terminal, .astro files are ignored entirely. Instead, you can use the astro check CLI command to check both .astro and .ts files. This plugin also supports importing .astro files from .ts files (which can be useful for re-exporting).

>> npm install @astrojs/ts-plugin

After installing the Astro TypeScript plugin, you can use the 'astro check' command to check both '.astro' and '.ts' files. Add the following code to your tsconfig.json

{
  "compilerOptions": {
    "plugins": [
      {
        "name": "@astrojs/ts-plugin"
      },
    ],
  }
}
Advertisements