update
Some checks failed
deploy / deploy (push) Has been cancelled

This commit is contained in:
toom1996
2026-08-19 20:42:42 +08:00
parent e1552feb8c
commit 975c55feb2
8 changed files with 568 additions and 55 deletions

View File

@ -0,0 +1,19 @@
# 2026-08-19
## 修复 RunwayLooksDetail.astro 的红线(TS 严格模式报错)
- 文件:`src/components/RunwayLooksDetail.astro`(一个 Alpine 灯箱详情组件)。
- 根因:项目 `tsconfig.json` 继承 `astro/tsconfigs/strict`(含 `noImplicitThis`)。该文件 `<script>` 里有两类红线:
1. **`this` 隐式 any**(ts2683):Alpine 组件 `Alpine.data("articleView", () => ({...}))` 的方法里直接用 `this.xxx`,无类型注解。
2. **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` 红线,套用同样的「接口标注返回类型」修法即可。
## 用户偏好(本次交互印证)
- 用户倾向于「直接帮我修好」,而非只给方案;遇到红线/报错类诉求,动手修复并实证验证(构建/类型检查)比单纯解释更受认可。