typescript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript
TypeScript
Use this skill to configure, diagnose, and fix TypeScript projects. It is a workflow, not a language reference: the type system syntax is assumed knowledge, and the focus is on compiler behavior, configuration, and cryptic failures.
Helper Scripts Available:
- - Detects package manager, TypeScript version, a side-by-side native compiler (TypeScript 7 alias) and which tsconfig each
scripts/inspect_typescript.pyscript targets, tsconfig files with extends chains and effective flags, framework checker (vue-tsc, nuxi, svelte-check, astro), source files not covered by any tsconfig, monorepo markers, linter, runner, and the recommended typecheck commandtypecheck* - - Runs type-checking through the detected package manager and summarizes errors by code and file
scripts/run_typecheck.py - - Measures compilation via
scripts/trace_perf.py, flags anomalies, optionally writes a compiler trace--extendedDiagnostics
<skill>--help<skill>.agents/skills/....claude/skills/...本技能用于配置、诊断和修复TypeScript项目。这是一套工作流,而非语言参考:默认你已掌握类型系统语法,重点关注编译器行为、配置及疑难故障解决。
可用辅助脚本:
- - 检测包管理器、TypeScript版本、并行原生编译器(TypeScript 7别名)、每个
scripts/inspect_typescript.py脚本指向的tsconfig、带有继承链的tsconfig文件及有效标志、框架检查器(vue-tsc、nuxi、svelte-check、astro)、未被任何tsconfig覆盖的源文件、monorepo标记、检查器、运行器,以及推荐的类型检查命令typecheck* - - 通过检测到的包管理器运行类型检查,并按错误代码和文件汇总错误信息
scripts/run_typecheck.py - - 通过
scripts/trace_perf.py测量编译性能,标记异常情况,可选生成编译器跟踪日志--extendedDiagnostics
<skill>--help<skill>.agents/skills/....claude/skills/...Decision Tree
决策树
User task -> Existing project?
- Yes -> Project docs (CLAUDE.md/AGENTS.md/README) or package.json already
name the typecheck command, and it is a single tsconfig without
extends? -> Use that command directly; skip the helper scripts.
Otherwise run: python <skill>/scripts/inspect_typescript.py --root <project>
Use detected manager, tsconfig chain, effective flags, monorepo layout.
- No -> Create the smallest strict tsconfig matching the runtime.
Do not paste large config templates; set only what the project needs.
Next -> What is the symptom?
- Type errors after a change -> run_typecheck.py, then Error Playbook below
- Cryptic compiler error -> references/error-playbook.md
- "Cannot find module" / imports -> references/module-resolution.md
- Slow tsc / slow editor -> trace_perf.py, then Performance below
- Audit / harden a green project -> Audit & Hardening below
- JavaScript to TypeScript -> references/migration.md
- TypeScript 7 / native compiler -> references/typescript-7-migration.md
- Monorepo / project references -> references/monorepo.md
- New tsconfig / stricter flags -> Configuration belowThe helper scripts pay off in monorepos and extends chains; on a small project with one tsconfig, reading the config and running the checker directly is faster.
用户任务 -> 是否为已有项目?
- 是 -> 项目文档(CLAUDE.md/AGENTS.md/README)或package.json已指定类型检查命令,且仅包含一个无继承的tsconfig? -> 直接使用该命令;跳过辅助脚本。
否则运行:python <skill>/scripts/inspect_typescript.py --root <project>
使用检测到的管理器、tsconfig继承链、有效标志、monorepo布局。
- 否 -> 创建与运行时匹配的最小化严格tsconfig。
请勿粘贴大型配置模板;仅设置项目所需的选项。
下一步 -> 症状是什么?
- 修改后出现类型错误 -> 运行run_typecheck.py,然后参考下方错误手册
- 晦涩的编译器错误 -> references/error-playbook.md
- "Cannot find module" / 导入问题 -> references/module-resolution.md
- tsc运行缓慢 / 编辑器卡顿 -> 运行trace_perf.py,然后参考下方性能优化部分
- 审计/强化已正常检查的项目 -> 参考下方审计与强化部分
- JavaScript迁移至TypeScript -> references/migration.md
- TypeScript 7 / 原生编译器 -> references/typescript-7-migration.md
- Monorepo / 项目引用 -> references/monorepo.md
- 新建tsconfig / 更严格的标志 -> 参考下方配置部分辅助脚本在monorepo和继承链场景中优势明显;对于只有一个tsconfig的小型项目,直接读取配置并运行检查器速度更快。
Core Workflow
核心工作流
- Inspect first: discover the package manager, tsconfig extends chain, effective flags, and monorepo layout before changing anything.
- Match the project: keep its /
modulepair, its extends chain, and its package manager. Do not switch resolution strategies to silence one error.moduleResolution - Prefer the minimal fix: one flag, one type annotation, one dependency — not a rewritten tsconfig.
- Verify narrowly first: or
run_typecheck.py --project <pkg tsconfig>before a full-repo check.--files - Never "fix" an error with ,
any, orasto get to green. Reaching for them means the actual cause is not yet understood; find it first, and use targeted narrowing or a documented@ts-ignoreonly as a last resort. One pragmatic exception: casts at test mock boundaries (@ts-expect-error) are acceptable in test files; production code is not.mock as unknown as Service
- 先检查:在进行任何更改前,先发现包管理器、tsconfig继承链、有效标志及monorepo布局。
- 匹配项目:保留其/
module配对、继承链及包管理器。请勿为了消除单个错误而切换解析策略。moduleResolution - 优先最小化修复:仅修改一个标志、一个类型注解或一个依赖——而非重写整个tsconfig。
- 先进行窄范围验证:在全仓库检查前,使用或
run_typecheck.py --project <pkg tsconfig>进行验证。--files - 切勿使用、
any或as来“修复”错误以达到无报错状态。使用这些手段意味着尚未找到真正的问题根源;先找到根源,仅在万不得已时使用针对性的类型收窄或有文档记录的@ts-ignore。一个务实的例外:在测试模拟边界处的类型转换(@ts-expect-error)在测试文件中是可接受的;但生产代码中不允许。mock as unknown as Service
Configuration
配置
Direction for new or hardened configs (adopt, do not paste wholesale):
- is the baseline; add
strict: trueandnoUncheckedIndexedAccesswhen the codebase can absorb them.noImplicitOverride - In an existing project, enable new strictness flags one at a time and fix fallout per flag; do not flip several at once.
- /
module:moduleResolutionfor Node libraries and servers,NodeNext/ESNextfor bundled apps. These two options must be chosen as a pair; see references/module-resolution.md.bundler - is a pragmatic default; remove it only when debugging a broken dependency's types.
skipLibCheck: true - Respect the extends chain: change the leaf config for a package-local need, the base config for a repo-wide policy.
- Before a compiler-major migration, read the installed version from ; dependency ranges and global
node_modules/typescript/package.jsoncan describe a different compiler. For TypeScript 7, follow references/typescript-7-migration.md.tsc - Order new flags by fixing cost: /
noUnusedLocals(cheap) ->noUnusedParameters/noFallthroughCasesInSwitch(near-free) ->noImplicitOverride->exactOptionalPropertyTypes(most expensive, last).noUncheckedIndexedAccess
针对新建或强化配置的指导(采用而非全盘粘贴):
- 是基线;当代码库能够承受时,添加
strict: true和noUncheckedIndexedAccess。noImplicitOverride - 在现有项目中,一次启用一个新的严格性标志,并针对每个标志修复问题;切勿同时启用多个。
- /
module:Node库和服务器使用moduleResolution,打包应用使用NodeNext/ESNext。这两个选项必须配对选择;详见references/module-resolution.md。bundler - 是务实的默认值;仅在调试依赖包的类型问题时才移除它。
skipLibCheck: true - 尊重继承链:针对包本地需求修改叶子节点配置,针对仓库全局策略修改基础配置。
- 在进行编译器大版本迁移前,从读取已安装的版本;依赖范围和全局
node_modules/typescript/package.json可能对应不同的编译器。对于TypeScript 7迁移,请遵循references/typescript-7-migration.md。tsc - 按修复成本排序新标志:/
noUnusedLocals(成本低)->noUnusedParameters/noFallthroughCasesInSwitch(几乎无成本)->noImplicitOverride->exactOptionalPropertyTypes(成本最高,最后启用)。noUncheckedIndexedAccess
Framework Projects (Vue, Nuxt, Svelte, Astro)
框架项目(Vue、Nuxt、Svelte、Astro)
Plain silently ignores // component files — a green run proves nothing there. Use the framework's checker:
tsc --noEmit.vue.svelte.astro| Stack | Typecheck command |
|---|---|
| Vue SFC | |
| Nuxt | |
| Svelte / SvelteKit | |
| Astro | |
Framework-generated tsconfig (Nuxt , SvelteKit , Astro's base): never edit generated files — the effective flags may live there, not in the root config. Set options through the framework config (e.g. in ) or the root tsconfig that extends the generated one. Template type errors surface as (TS18048) — the fix is in the SFC template or props; see references/error-playbook.md.
.nuxt/tsconfig.*.svelte-kit/tsconfig.jsontypescript.tsConfignuxt.config.ts__VLS_ctx.x is possibly 'undefined'普通的会忽略//组件文件——无报错运行并不代表这些文件没有问题。请使用框架专属的检查器:
tsc --noEmit.vue.svelte.astro| 技术栈 | 类型检查命令 |
|---|---|
| Vue SFC | |
| Nuxt | |
| Svelte / SvelteKit | |
| Astro | |
框架生成的tsconfig(Nuxt的、SvelteKit的、Astro的基础配置):切勿编辑生成的文件——有效标志可能存在于这些文件中,而非根配置。通过框架配置(如中的)或继承自生成配置的根tsconfig来设置选项。模板类型错误会表现为(TS18048)——修复方案在SFC模板或props中;详见references/error-playbook.md。
.nuxt/tsconfig.*.svelte-kit/tsconfig.jsonnuxt.config.tstypescript.tsConfig__VLS_ctx.x is possibly 'undefined'Audit & Hardening
审计与强化
For "audit the TypeScript setup" or "tighten types" on a project that already checks green:
- Setup: pinned in devDependencies; a
typescriptscript in package.json; CI runs it. "Pinned" here means at least a caret major-compatible range (typecheck) with a committed lockfile; prefer a tilde minor-compatible range (^6.0.3) or an exact pin (~6.0.3) when a compiler patch has broken the build before. In a side-by-side compiler setup, audit every6.0.3script, not justtypecheck*: match each against the CI workflow and report any (e.g. a nativetypecheck) that CI never runs.typecheck:ts7lists the native compiler and each script's target tsconfig.inspect_typescript.py - Coverage: every /
.ts/.tsxfile falls inside some tsconfig's.vue(inspect_typescript.py reports uncovered files) — uncovered code is never type-checked.include - Effective strictness: read effective flags from the inspect output; framework-generated configs may set flags the root config does not show.
- Hygiene grep: ,
: any,as any,@ts-ignore, and non-null assertions (the postfix@ts-expect-erroroperator). Prioritize exported/public APIs and component props > server boundaries > internal utilities. Replace assertions with real guards or type predicates; make a prop required instead of optional when every call site passes it.x! - Enable missing strictness flags one at a time, cheapest first (order above), fixing fallout per flag.
Linter rules ( and friends) are the linter's domain, not this skill's: note them in audit findings, fix them via lint config.
no-explicit-any针对“审计TypeScript配置”或“收紧类型”的已正常检查项目:
- 基础设置:在devDependencies中固定版本;package.json中有
typescript脚本;CI会运行该脚本。此处的“固定”指至少使用兼容主版本的脱字符范围(typecheck)并提交lockfile;当编译器补丁曾导致构建失败时,优先使用兼容次版本的波浪号范围(^6.0.3)或精确固定版本(~6.0.3)。在并行编译器设置中,审计所有6.0.3脚本,而非仅typecheck*:将每个脚本与CI工作流匹配,并报告任何CI从未运行的脚本(如原生的typecheck)。typecheck:ts7会列出原生编译器及每个脚本的目标tsconfig。inspect_typescript.py - 覆盖范围:每个/
.ts/.tsx文件都被某个tsconfig的.vue覆盖(inspect_typescript.py会报告未被覆盖的文件)——未被覆盖的代码永远不会被类型检查。include - 有效严格性:从检查输出中读取有效标志;框架生成的配置可能设置了根配置未显示的标志。
- 卫生检查:搜索、
: any、as any、@ts-ignore以及非空断言(后缀@ts-expect-error操作符)。优先处理导出/公共API和组件props > 服务器边界 > 内部工具。用真实的类型守卫或类型谓词替换断言;当每个调用站点都传递某个props时,将其设为必填而非可选。x! - 按成本从低到高的顺序(如上所述)一次启用一个缺失的严格性标志,并针对每个标志修复问题。
检查器规则(等)属于检查器的范畴,而非本技能:在审计结果中提及它们,通过检查器配置进行修复。
no-explicit-anyError Playbook (quick)
错误手册(速查)
Full catalog with causes and prioritized fixes: references/error-playbook.md.
| Error | First move |
|---|---|
| TS2307 Cannot find module | Check |
| TS2742 The inferred type cannot be named | Export the referenced type explicitly or annotate the declaration's return type |
| TS2589 Type instantiation is excessively deep | Break the recursion: simplify generic constraints, split unions, alias intermediate types |
| Excessive stack depth comparing types | Replace large type intersections with |
| TS5101 'baseUrl' is deprecated | Delete |
| TypeScript 7 rejects a deprecated compiler option | Upgrade through TypeScript 6, remove |
| TypeScript 7 reports missing Node/test globals | Set |
| A framework checker or tool fails after installing TypeScript 7 | Check its TypeScript peer range and compiler-API dependency; keep TypeScript 6 side by side when the tool has not added TypeScript 7 support |
| Template error in a Vue SFC: make the prop required or default it, or guard in the template |
| Editor shows errors CLI does not (or reverse) | Compare the TypeScript versions: editor's bundled TS vs workspace |
包含原因和优先修复方案的完整目录:references/error-playbook.md。
| 错误 | 第一步操作 |
|---|---|
| TS2307 Cannot find module | 检查 |
| TS2742 The inferred type cannot be named | 显式导出引用的类型,或为声明的返回类型添加注解 |
| TS2589 Type instantiation is excessively deep | 打破递归:简化泛型约束、拆分联合类型、为中间类型设置别名 |
| 类型比较时栈溢出 | 用 |
| TS5101 'baseUrl' is deprecated | 删除 |
| TypeScript 7拒绝已弃用的编译器选项 | 先升级至TypeScript 6,移除 |
| TypeScript 7报告缺少Node/测试全局变量 | 显式设置 |
| 安装TypeScript 7后框架检查器或工具失败 | 检查其TypeScript peer依赖范围和编译器API依赖;当工具尚未支持TypeScript 7时,保持TypeScript 6并行存在 |
| Vue SFC中的模板错误:将props设为必填或设置默认值,或在模板中添加守卫 |
| 编辑器显示的错误与CLI不一致(或反之) | 比较TypeScript版本:编辑器内置的TS与工作区 |
Performance
性能优化
When type-checking or the editor is slow:
bash
python <skill>/scripts/trace_perf.py --root .
python <skill>/scripts/trace_perf.py --root . --trace # deeper: compiler traceReading the result: high or dominating means type-level complexity (heavy generics, huge unions, deep conditional types) — fix the types. High / with modest check time means the program is too large — fix /, add project references, check that or generated output is not being picked up.
instantiationscheck_timetotal_timefileslinesincludeexcludenode_modulesStandard remedies in order: precise / -> -> -> project references for multi-package repos.
includeexcludeskipLibCheckincremental当类型检查或编辑器运行缓慢时:
bash
python <skill>/scripts/trace_perf.py --root .
python <skill>/scripts/trace_perf.py --root . --trace # 更深入:生成编译器跟踪日志解读结果:或占比例过高意味着类型层面复杂度高(复杂泛型、大型联合类型、深层条件类型)——需要优化类型。/数量多但检查时间适中意味着程序过大——需要优化/、添加项目引用、检查是否误包含了或生成的输出文件。
instantiationscheck_timetotal_timefileslinesincludeexcludenode_modules标准优化方案按顺序:精确设置/ -> 启用 -> 启用 -> 为多包仓库添加项目引用。
includeexcludeskipLibCheckincrementalCommon Failure Modes
常见失败模式
- aliases fail at runtime: tsconfig
pathsare compile-time only; the bundler or runtime needs its own alias config. See references/module-resolution.md.paths - Conflicting versions: duplicate
@types(or react) across the tree; align versions or set@types/nodeexplicitly.compilerOptions.types - Stale build state: delete (and
.tsbuildinfo) after config changes that should have changed the output but seemingly did not.node_modules/.cache - Editor vs CLI disagree: different TypeScript versions; point the editor to the workspace version.
- ESM/CJS mixing: of an ESM-only package or default-import mismatch; see references/module-resolution.md interop table.
require - Monorepo edits not picked up: project references need and a build step (
composite: true); see references/monorepo.md.tsc -b
- 别名在运行时失效:tsconfig的
paths仅在编译时生效;打包器或运行时需要单独的别名配置。详见references/module-resolution.md。paths - 版本冲突:树中存在重复的
@types(或react);统一版本或显式设置@types/node。compilerOptions.types - 构建状态过时:在配置更改后,若输出未按预期变化,删除(及
.tsbuildinfo)。node_modules/.cache - 编辑器与CLI结果不一致:TypeScript版本不同;将编辑器指向工作区版本。
- ESM/CJS混合使用:ESM-only包或默认导入不匹配;详见references/module-resolution.md中的互操作表。
require - Monorepo修改未被识别:项目引用需要及构建步骤(
composite: true);详见references/monorepo.md。tsc -b
Reference Files
参考文件
- - Cryptic compiler errors: cause and prioritized fixes
references/error-playbook.md - - module/moduleResolution pairs, ESM/CJS interop, paths, exports maps
references/module-resolution.md - - Incremental JavaScript-to-TypeScript migration
references/migration.md - - Compiler migration to TypeScript 7, including TypeScript 6 compatibility and framework constraints
references/typescript-7-migration.md - - Project references, composite builds, workspace typecheck order
references/monorepo.md
- - 晦涩编译器错误:原因及优先修复方案
references/error-playbook.md - - module/moduleResolution配对、ESM/CJS互操作、paths、exports映射
references/module-resolution.md - - JavaScript至TypeScript的增量迁移
references/migration.md - - 迁移至TypeScript 7的编译器指南,包括TypeScript 6兼容性及框架约束
references/typescript-7-migration.md - - 项目引用、复合构建、工作区类型检查顺序
references/monorepo.md