You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Astro中JSX是否有类型定义?@typescript-eslint规则报错求助

Astro JSX类型定义与@typescript-eslint/no-unsafe-return报错解决

Astro的JSX有官方内置的类型定义,你找到的node_modules/astro/astro-jsx.d.ts就是对应的类型声明文件,以下是具体的解决方法和使用方式:

快速解决报错:指定map回调的返回类型

在.map()的回调函数里明确标注返回类型为Astro.JSX.Element,就能让TypeScript识别JSX元素的类型,避免被判定为any,从而绕过ESLint的@typescript-eslint/no-unsafe-return报错:

---
const cards = [
    {
        href:"https://docs.astro.build/",
        title:"Documentation",
        body:"Learn how Astro works and explore the official API docs.",
    },
    {
        href: "https://astro.build/integrations/",
        title: "Integrations",
        body: "Supercharge your project with new frameworks and libraries.",
    },
    {
        href: "https://astro.build/themes/",
        title: "Themes",
        body: "Explore a galaxy of community-built starter themes.",
    }
];
---

<main>
    {cards.map((card): Astro.JSX.Element => (
        <div>{card.href}</div>
    ))}
</main>

增强类型安全:给数组定义明确类型(可选)

如果想进一步提升代码的类型严谨性,可以先给cards数组定义接口类型,让每个card的属性也获得类型校验:

---
interface Card {
    href: string;
    title: string;
    body: string;
}

const cards: Card[] = [
    {
        href:"https://docs.astro.build/",
        title:"Documentation",
        body:"Learn how Astro works and explore the official API docs.",
    },
    {
        href: "https://astro.build/integrations/",
        title: "Integrations",
        body: "Supercharge your project with new frameworks and libraries.",
    },
    {
        href: "https://astro.build/themes/",
        title: "Themes",
        body: "Explore a galaxy of community-built starter themes.",
    }
];
---

<main>
    {cards.map((card): Astro.JSX.Element => (
        <div>{card.href}</div>
    ))}
</main>

关于astro-jsx.d.ts的说明

这个文件是Astro内置的JSX类型声明,它定义了Astro.JSX命名空间,包含了Element(JSX元素类型)、IntrinsicElements(HTML标签对应的类型)等核心类型。只要你的项目正确安装了Astro(v2及以上版本已内置类型,无需额外安装@types/astro),TypeScript就能自动识别这些类型,不需要手动导入或修改这个文件。

内容的提问来源于stack exchange,提问作者Temoncher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:35:25