Skip to content

TypeScript

Astro 附带对 TypeScript. You can import .ts and .tsx files in your Astro project, write TypeScript code directly inside your Astro component 的内置支持,如果你愿意,甚至可以使用 astro.config.ts 文件进行 Astro 配置。

¥Astro ships with built-in support for TypeScript. You can import .ts and .tsx files in your Astro project, write TypeScript code directly inside your Astro component, and even use an astro.config.ts file for your Astro configuration if you like.

使用 TypeScript,你可以通过在代码中定义对象和组件的形状来防止运行时出现错误。例如,如果你使用 TypeScript 到 输入组件的 props,如果你设置的组件不接受的 prop,你将在编辑器中收到错误。

¥Using TypeScript, you can prevent errors at runtime by defining the shapes of objects and components in your code. For example, if you use TypeScript to type your component’s props, you’ll get an error in your editor if you set a prop that your component doesn’t accept.

你无需在 Astro 项目中编写 TypeScript 代码即可从中受益。Astro 始终将你的组件代码视为 TypeScript,并且 Astro VSCode 扩展 将尽可能地进行推断,以在编辑器中提供自动补齐、提示和错误。

¥You don’t need to write TypeScript code in your Astro projects to benefit from it. Astro always treats your component code as TypeScript, and the Astro VSCode Extension will infer as much as it can to provide autocompletion, hints, and errors in your editor.

Astro 开发服务器不会执行任何类型检查,但你可以使用 单独的脚本 从命令行检查类型错误。

¥The Astro dev server won’t perform any type checking, but you can use a separate script to check for type errors from the command line.

¥Setup

Astro 入门项目在你的项目中包含 tsconfig.json 文件。即使你不编写 TypeScript 代码,此文件也很重要,以便 Astro 和 VS Code 等工具知道如何理解你的项目。如果没有 tsconfig.json 文件,编辑器将无法完全支持某些功能(例如 npm 包导入)。如果你手动安装 Astro,请务必自行创建此文件。

¥Astro starter projects include a tsconfig.json file in your project. 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.

¥TSConfig templates

Astro 中包含三个可扩展的 tsconfig.json 模板:basestrictstrictestbase 模板支持现代 JavaScript 功能,也用作其他模板的基础。如果你计划在项目中编写 TypeScript,我们建议使用 strictstrictest。你可以在 astro/tsconfigs/ 处查看并比较三种模板配置。

¥Three extensible tsconfig.json templates are included in Astro: base, strict, and strictest. The base template enables support for modern JavaScript features and is also used as a basis for the other templates. We recommend using strict or strictest if you plan to write TypeScript in your project. You can view and compare the three template configurations at astro/tsconfigs/.

要从其中一个模板继承,请使用 extends 设置

¥To inherit from one of the templates, use the extends setting:

tsconfig.json
{
"extends": "astro/tsconfigs/base"
}

此外,我们建议按如下方式设置 includeexclude,以从 Astro 类型中受益并避免检查构建文件:

¥Additionally, we recommend setting include and exclude as follows to benefit from Astro types and avoid checking built files:

tsconfig.json
{
"extends": "astro/tsconfigs/base",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}

你可以创建 src/env.d.ts 作为添加自定义类型声明的约定,或者在没有 tsconfig.json 的情况下从 Astro 类型中受益:

¥You can create src/env.d.ts as a convention for adding custom types declarations, or to benefit from Astro types if you don’t have a tsconfig.json:

src/env.d.ts
// Custom types declarations
declare var myString: string;
// Astro types, not necessary if you already have a tsconfig.json
/// <reference path="../.astro/types.d.ts" />

TypeScript 编辑器插件

标题部分 TypeScript 编辑器插件

¥TypeScript editor plugin

当你不使用 官方 Astro VS Code 扩展 时,可以单独安装 Astro TypeScript 插件。此插件由 VSCode 扩展自动安装和配置,你无需同时安装两者。此插件仅在编辑器中运行。在终端中运行 tsc 时,.astro 文件将被完全忽略。相反,你可以使用 astro check CLI 命令 检查 .astro.ts 文件。此插件还支持从 .ts 文件导入 .astro 文件(这对于重新导出很有用)。

¥The Astro TypeScript plugin can be installed separately when you are not using the official Astro VS Code extension. This plugin is automatically installed and configured by the VSCode extension, and you do not need to install both. 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

然后,将以下内容添加到你的 tsconfig.json

¥Then, add the following to your tsconfig.json:

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

要检查插件是否正常工作,请创建一个 .ts 文件并将 Astro 组件导入其中。你应该不会收到来自编辑器的警告消息。

¥To check that the plugin is working, create a .ts file and import an Astro component into it. You should have no warning messages from your editor.

¥UI Frameworks

如果你的项目使用 用户界面框架,则可能需要根据框架进行其他设置。请参阅你的框架的 TypeScript 文档以获取更多信息。(VueReactPreact坚硬的

¥If your project uses a UI framework, additional settings depending on the framework might be needed. Please see your framework’s TypeScript documentation for more information. (Vue, React, Preact, Solid)

¥Type Imports

尽可能使用显式类型导入和导出。

¥Use explicit type imports and exports whenever possible.

import { SomeType } from './script';
import type { SomeType } from './script';

这样,你就可以避免 Astro 的打包程序可能会尝试错误地将导入的类型打包为 JavaScript 的极端情况。

¥This way, you avoid edge cases where Astro’s bundler may try to incorrectly bundle your imported types as if they were JavaScript.

你可以配置 TypeScript 以在 tsconfig.json 文件中强制执行类型导入。将 verbatimModuleSyntax 设置为 true。TypeScript 将检查你的导入并告诉你何时应该使用 import type。我们的所有预设中默认启用此设置。

¥You can configure TypeScript to enforce type imports in your tsconfig.json file. Set verbatimModuleSyntax to true. TypeScript will check your imports and tell you when import type should be used. This setting is enabled by default in all our presets.

tsconfig.json
{
"compilerOptions": {
"verbatimModuleSyntax": true
}
}

¥Import Aliases

Astro 支持你在 tsconfig.json paths 配置中定义的 import aliases阅读我们的指南 了解更多信息。

¥Astro supports import aliases that you define in your tsconfig.json paths configuration. Read our guide to learn more.

src/pages/about/nate.astro
---
import HelloWorld from '@components/HelloWorld.astro';
import Layout from '@layouts/Layout.astro';
---
tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["src/components/*"],
"@layouts/*": ["src/layouts/*"]
}
}
}

扩展 windowglobalThis

标题部分 扩展 window 和 globalThis

¥Extending window and globalThis

你可能想要向全局对象添加属性。你可以通过使用 declare 关键字将顶层声明添加到 env.d.ts 文件中来完成此操作:

¥You may want to add a property to the global object. You can do this by adding top-level declarations using the declare keyword to your env.d.ts file:

src/env.d.ts
declare var myString: string;
declare function myFunction(): boolean;

这将为 globalThis.myStringglobalThis.myFunction,以及 window.myStringwindow.myFunction 提供输入。

¥This will provide typing to globalThis.myString and globalThis.myFunction, as well as window.myString and window.myFunction.

请注意,window 仅在客户端代码中可用。globalThis 在服务器端和客户端均可用,但其服务器端值不会与客户端共享。

¥Note that window is only available in client-side code. globalThis is available both server-side and client-side, but its server-side value won’t be shared with the client.

如果你只想在 window 对象上键入属性,请提供 Window 接口:

¥If you only want to type a property on the window object, provide a Window interface instead:

src/env.d.ts
interface Window {
myFunction(): boolean;
}

¥Component Props

Astro 支持通过 TypeScript 输入组件属性。要启用此功能,请将 TypeScript Props 接口添加到组件 frontmatter 中。可以使用 export 语句,但不是必需的。当你在另一个模板中使用该组件时,Astro VSCode 扩展 将自动查找 Props 接口并为你提供适当的 TS 支持。

¥Astro supports typing your component props via TypeScript. To enable, add a TypeScript Props interface to your component frontmatter. An export statement may be used, but is not necessary. The Astro VSCode Extension will automatically look for the Props interface and give you proper TS support when you use that component inside another template.

src/components/HelloProps.astro
---
interface Props {
name: string;
greeting?: string;
}
const { greeting = 'Hello', name } = Astro.props;
---
<h2>{greeting}, {name}!</h2>

常见的属性类型模式

标题部分 常见的属性类型模式

¥Common prop type patterns

  • 如果你的组件不使用 props 或 slotted 内容,你可以使用 type Props = Record<string, never>

  • 如果你的组件必须将子组件传递到其默认插槽,你可以使用 type Props = { children: any; }; 来强制执行此操作。

¥Type Utilities

Added in: astro@1.6.0

Astro 附带了一些用于常见属性类型模式的内置工具类型。这些可以在 astro/types 入口点下找到。

¥Astro comes with some built-in utility types for common prop type patterns. These are available under the astro/types entrypoint.

¥Built-in HTML attributes

Astro 提供 HTMLAttributes 类型来检查你的标记是否使用有效的 HTML 属性。你可以使用这些类型来帮助构建组件属性。

¥Astro provides the HTMLAttributes type to check that your markup is using valid HTML attributes. You can use these types to help build component props.

例如,如果你正在构建 <Link> 组件,则可以执行以下操作以在组件的 prop 类型中镜像 <a> 标记的默认 HTML 属性。

¥For example, if you were building a <Link> component, you could do the following to mirror the default HTML attributes for <a> tags in your component’s prop types.

src/components/Link.astro
---
import type { HTMLAttributes } from 'astro/types';
// use a `type`
type Props = HTMLAttributes<'a'>;
// or extend with an `interface`
interface Props extends HTMLAttributes<'a'> {
myProp?: boolean;
}
const { href, ...attrs } = Astro.props;
---
<a href={href} {...attrs}>
<slot />
</a>

还可以通过在 .d.ts 文件中重新声明 astroHTML.JSX 命名空间来扩展默认 JSX 定义以添加非标准属性。

¥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.

src/custom-attributes.d.ts
declare namespace astroHTML.JSX {
interface HTMLAttributes {
'data-count'?: number;
'data-label'?: string;
}
// Add a CSS custom property to the style object
interface CSSProperties {
'--theme-color'?: 'black' | 'white';
}
}

¥ComponentProps type

Added in: astro@4.3.0

此类型导出允许你引用另一个组件接受的 Props,即使该组件不直接导出该 Props 类型。

¥This type export allows you to reference the Props accepted by another component, even if that component doesn’t export that Props type directly.

以下示例显示如何使用 astro/types 中的 ComponentProps 实用程序来引用 <Button /> 组件的 Props 类型:

¥The following example shows using the ComponentProps utility from astro/types to reference a <Button /> component’s Props types:

src/pages/index.astro
---
import type { ComponentProps } from 'astro/types';
import Button from "./Button.astro";
type ButtonProps = ComponentProps<typeof Button>;
---

¥Polymorphic type

Added in: astro@2.5.0

Astro 包含一个辅助程序,可以更轻松地构建可以渲染为不同 HTML 元素且具有完全类型安全性的组件。这对于像 <Link> 这样的组件很有用,这些组件可以根据传递给它的 props 渲染为 <a><button>

¥Astro includes a helper to make it easier to build components that can render as different HTML elements with full type safety. This is useful for components like <Link> that can render as either <a> or <button> depending on the props passed to it.

下面的示例实现了一个完全类型化的多态组件,可以渲染为任何 HTML 元素。HTMLTag 类型用于确保 as 属性是有效的 HTML 元素。

¥The example below implements a fully-typed, polymorphic component that can render as any HTML element. The HTMLTag type is used to ensure that the as prop is a valid HTML element.

---
import type { HTMLTag, Polymorphic } from 'astro/types';
type Props<Tag extends HTMLTag> = Polymorphic<{ as: Tag }>;
const { as: Tag, ...props } = Astro.props;
---
<Tag {...props} />

推断 getStaticPaths() 类型

标题部分 推断 getStaticPaths() 类型

¥Infer getStaticPaths() types

Added in: astro@2.1.0

Astro 包含用于处理动态路由的 getStaticPaths() 函数返回的类型的辅助程序。

¥Astro includes helpers for working with the types returned by your getStaticPaths() function for dynamic routes.

你可以用 InferGetStaticParamsType 得到 Astro.params 的类型,用 InferGetStaticPropsType 得到 Astro.props 的类型:

¥You can get the type of Astro.params with InferGetStaticParamsType and the type of Astro.props with InferGetStaticPropsType:

src/pages/posts/[...id].astro
---
import type { InferGetStaticParamsType, InferGetStaticPropsType, GetStaticPaths } from 'astro';
export const getStaticPaths = (async () => {
const posts = await getCollection('blog');
return posts.map((post) => {
return {
params: { id: post.id },
props: { draft: post.data.draft, title: post.data.title },
};
});
}) satisfies GetStaticPaths;
type Params = InferGetStaticParamsType<typeof getStaticPaths>;
type Props = InferGetStaticPropsType<typeof getStaticPaths>;
const { id } = Astro.params as Params;
// ^? { id: string; }
const { title } = Astro.props;
// ^? { draft: boolean; title: string; }
---

¥Type checking

要在编辑器中查看类型错误,请确保你已安装 Astro VS Code 扩展。请注意,astro startastro build 命令将使用 esbuild 转译代码,但不会运行任何类型检查。为了防止代码包含 TypeScript 错误而无法构建,请将 package.json 中的 “build” 脚本更改为以下内容:

¥To see type errors in your editor, please make sure that you have the Astro VS Code extension 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:

package.json
"scripts": {
"build": "astro build",
"build": "astro check && astro build",
},
Read more about .ts file imports in Astro.
Read more about TypeScript Configuration.

¥Troubleshooting

同时输入多个 JSX 框架时出错

标题部分 同时输入多个 JSX 框架时出错

¥Errors typing multiple JSX frameworks at the same time

在同一个项目中使用多个 JSX 框架时可能会出现问题,因为每个框架在 tsconfig.json 中需要不同的、有时甚至是冲突的设置。

¥An issue may arise when using multiple JSX frameworks in the same project, as each framework requires different, sometimes conflicting, settings inside tsconfig.json.

解决方案:根据你最常用的框架将 jsxImportSource 设置 设置为 react(默认)、preactsolid-js。然后,在来自不同框架的任何冲突文件中使用 编译指示注释

¥Solution: Set the jsxImportSource setting to react (default), preact or solid-js depending on your most-used framework. Then, use a pragma comment inside any conflicting file from a different framework.

对于 jsxImportSource: react 的默认设置,你可以使用:

¥For the default setting of jsxImportSource: react, you would use:

// For Preact
/** @jsxImportSource preact */
// For Solid
/** @jsxImportSource solid-js */
Astro 中文网 - 粤ICP备13048890号