2.6 KiB
2.6 KiB
2026-08-19
修复 RunwayLooksDetail.astro 的红线(TS 严格模式报错)
- 文件:
src/components/RunwayLooksDetail.astro(一个 Alpine 灯箱详情组件)。 - 根因:项目
tsconfig.json继承astro/tsconfigs/strict(含noImplicitThis)。该文件<script>里有两类红线:this隐式 any(ts2683):Alpine 组件Alpine.data("articleView", () => ({...}))的方法里直接用this.xxx,无类型注解。- DOM 属性类型不匹配(ts2339/2531):
document.querySelector(...)返回Element却取.dataset/.offsetTop/.style;getElementById("lb-image")取.src/.alt(需HTMLImageElement);querySelectorAll(...)结果按Element取.dataset/.style。
- 修复:
- 新增
type ArticleView = {...}接口,给Alpine.data回调标注返回类型(): ArticleView => ({...}),使对象字面量被上下文类型化,this推断为ArticleView,红线 1 消除。 - 给 DOM 查询补正确元素类型:
getImageElement返回HTMLElement | null(querySelector<HTMLElement>);getElementById("lb-image") as HTMLImageElement | null;getElementById("lb-thumbs") as HTMLElement | null+querySelector<HTMLElement>;querySelectorAll<HTMLElement>;entry.target as HTMLElement。红线 2 消除。
- 新增
- 验证:把
<script>抽成临时.ts(注入import type * as AlpineNS from "alpinejs"; declare global { const Alpine: AlpineNS.Alpine }),用node node_modules/typescript/bin/tsc --noEmit --strict --skipLibCheck --ignoreConfig --target es2020 --lib dom,es2020 --module esnext --moduleResolution bundler检查,零报错;npm run build通过。
项目小坑补充(复用 Astro 脚本类型检查)
- 本仓库未安装
typescript(也不在 package.json),npx tsc会误装错误的tsc@2.0.3包。需npm i typescript --no-save后再用node node_modules/typescript/bin/tsc检查;--moduleResolution node(node10) 在新版 TS 已移除,改用bundler;命令行显式传文件时需加--ignoreConfig(否则报 TS5112 因存在 tsconfig.json)。 astro check也未安装。临时抽<script>+ tsc --strict 是可接受的替代验证方式。- 提醒:同类 Alpine 组件(
RunwayLooks.astro、src/components/pages/article.astro等)若后续也出现this红线,套用同样的「接口标注返回类型」修法即可。
用户偏好(本次交互印证)
- 用户倾向于「直接帮我修好」,而非只给方案;遇到红线/报错类诉求,动手修复并实证验证(构建/类型检查)比单纯解释更受认可。