typescript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript

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:
  • scripts/inspect_typescript.py
    - Detects package manager, TypeScript version, a side-by-side native compiler (TypeScript 7 alias) and which tsconfig each
    typecheck*
    script 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 command
  • scripts/run_typecheck.py
    - Runs type-checking through the detected package manager and summarizes errors by code and file
  • scripts/trace_perf.py
    - Measures compilation via
    --extendedDiagnostics
    , flags anomalies, optionally writes a compiler trace
<skill>
means the path to this local skill folder. Run helper scripts with
--help
when usage is unclear or before first use in a session. Prefer using helper scripts as black-box tools. Read or modify their source only when debugging the skill itself or when behavior is unclear. In a git worktree, resolve
<skill>
to the skill's absolute path: a relative
.agents/skills/...
(or
.claude/skills/...
) path may be gitignored and absent from the worktree checkout.
本技能用于配置、诊断和修复TypeScript项目。这是一套工作流,而非语言参考:默认你已掌握类型系统语法,重点关注编译器行为、配置及疑难故障解决。
可用辅助脚本:
  • scripts/inspect_typescript.py
    - 检测包管理器、TypeScript版本、并行原生编译器(TypeScript 7别名)、每个
    typecheck*
    脚本指向的tsconfig、带有继承链的tsconfig文件及有效标志、框架检查器(vue-tsc、nuxi、svelte-check、astro)、未被任何tsconfig覆盖的源文件、monorepo标记、检查器、运行器,以及推荐的类型检查命令
  • scripts/run_typecheck.py
    - 通过检测到的包管理器运行类型检查,并按错误代码和文件汇总错误信息
  • scripts/trace_perf.py
    - 通过
    --extendedDiagnostics
    测量编译性能,标记异常情况,可选生成编译器跟踪日志
<skill>
指本地技能文件夹的路径。当用法不明确或首次在会话中使用时,使用
--help
参数运行辅助脚本。优先将辅助脚本作为黑盒工具使用。仅在调试技能本身或行为不明确时,才读取或修改其源代码。在git工作树中,需将
<skill>
解析为技能的绝对路径:相对路径
.agents/skills/...
(或
.claude/skills/...
)可能被git忽略,且在工作树检出中不存在。

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 below
The 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

核心工作流

  1. Inspect first: discover the package manager, tsconfig extends chain, effective flags, and monorepo layout before changing anything.
  2. Match the project: keep its
    module
    /
    moduleResolution
    pair, its extends chain, and its package manager. Do not switch resolution strategies to silence one error.
  3. Prefer the minimal fix: one flag, one type annotation, one dependency — not a rewritten tsconfig.
  4. Verify narrowly first:
    run_typecheck.py --project <pkg tsconfig>
    or
    --files
    before a full-repo check.
  5. Never "fix" an error with
    any
    ,
    as
    , or
    @ts-ignore
    to 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-expect-error
    only as a last resort. One pragmatic exception: casts at test mock boundaries (
    mock as unknown as Service
    ) are acceptable in test files; production code is not.
  1. 先检查:在进行任何更改前,先发现包管理器、tsconfig继承链、有效标志及monorepo布局。
  2. 匹配项目:保留其
    module
    /
    moduleResolution
    配对、继承链及包管理器。请勿为了消除单个错误而切换解析策略。
  3. 优先最小化修复:仅修改一个标志、一个类型注解或一个依赖——而非重写整个tsconfig。
  4. 先进行窄范围验证:在全仓库检查前,使用
    run_typecheck.py --project <pkg tsconfig>
    或
    --files
    进行验证。
  5. 切勿使用
    any
    、
    as
    或
    @ts-ignore
    来“修复”错误以达到无报错状态。使用这些手段意味着尚未找到真正的问题根源;先找到根源,仅在万不得已时使用针对性的类型收窄或有文档记录的
    @ts-expect-error
    。一个务实的例外:在测试模拟边界处的类型转换(
    mock as unknown as Service
    )在测试文件中是可接受的;但生产代码中不允许。

Configuration

配置

Direction for new or hardened configs (adopt, do not paste wholesale):
  • strict: true
    is the baseline; add
    noUncheckedIndexedAccess
    and
    noImplicitOverride
    when the codebase can absorb them.
  • In an existing project, enable new strictness flags one at a time and fix fallout per flag; do not flip several at once.
  • module
    /
    moduleResolution
    :
    NodeNext
    for Node libraries and servers,
    ESNext
    /
    bundler
    for bundled apps. These two options must be chosen as a pair; see references/module-resolution.md.
  • skipLibCheck: true
    is a pragmatic default; remove it only when debugging a broken dependency's types.
  • 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
    node_modules/typescript/package.json
    ; dependency ranges and global
    tsc
    can describe a different compiler. For TypeScript 7, follow references/typescript-7-migration.md.
  • Order new flags by fixing cost:
    noUnusedLocals
    /
    noUnusedParameters
    (cheap) ->
    noFallthroughCasesInSwitch
    /
    noImplicitOverride
    (near-free) ->
    exactOptionalPropertyTypes
    ->
    noUncheckedIndexedAccess
    (most expensive, last).
针对新建或强化配置的指导(采用而非全盘粘贴):
  • strict: true
    是基线;当代码库能够承受时,添加
    noUncheckedIndexedAccess
    和
    noImplicitOverride
    。
  • 在现有项目中,一次启用一个新的严格性标志,并针对每个标志修复问题;切勿同时启用多个。
  • module
    /
    moduleResolution
    :Node库和服务器使用
    NodeNext
    ,打包应用使用
    ESNext
    /
    bundler
    。这两个选项必须配对选择;详见references/module-resolution.md。
  • skipLibCheck: true
    是务实的默认值;仅在调试依赖包的类型问题时才移除它。
  • 尊重继承链:针对包本地需求修改叶子节点配置,针对仓库全局策略修改基础配置。
  • 在进行编译器大版本迁移前,从
    node_modules/typescript/package.json
    读取已安装的版本;依赖范围和全局
    tsc
    可能对应不同的编译器。对于TypeScript 7迁移,请遵循references/typescript-7-migration.md。
  • 按修复成本排序新标志:
    noUnusedLocals
    /
    noUnusedParameters
    (成本低)->
    noFallthroughCasesInSwitch
    /
    noImplicitOverride
    (几乎无成本)->
    exactOptionalPropertyTypes
    ->
    noUncheckedIndexedAccess
    (成本最高,最后启用)。

Framework Projects (Vue, Nuxt, Svelte, Astro)

框架项目(Vue、Nuxt、Svelte、Astro)

Plain
tsc --noEmit
silently ignores
.vue
/
.svelte
/
.astro
component files — a green run proves nothing there. Use the framework's checker:
StackTypecheck command
Vue SFC
vue-tsc --noEmit
Nuxt
npx nuxi typecheck
Svelte / SvelteKit
svelte-check
Astro
astro check
Framework-generated tsconfig (Nuxt
.nuxt/tsconfig.*
, SvelteKit
.svelte-kit/tsconfig.json
, 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.
typescript.tsConfig
in
nuxt.config.ts
) or the root tsconfig that extends the generated one. Template type errors surface as
__VLS_ctx.x is possibly 'undefined'
(TS18048) — the fix is in the SFC template or props; see references/error-playbook.md.
普通的
tsc --noEmit
会忽略
.vue
/
.svelte
/
.astro
组件文件——无报错运行并不代表这些文件没有问题。请使用框架专属的检查器:
技术栈类型检查命令
Vue SFC
vue-tsc --noEmit
Nuxt
npx nuxi typecheck
Svelte / SvelteKit
svelte-check
Astro
astro check
框架生成的tsconfig(Nuxt的
.nuxt/tsconfig.*
、SvelteKit的
.svelte-kit/tsconfig.json
、Astro的基础配置):切勿编辑生成的文件——有效标志可能存在于这些文件中,而非根配置。通过框架配置(如
nuxt.config.ts
中的
typescript.tsConfig
)或继承自生成配置的根tsconfig来设置选项。模板类型错误会表现为
__VLS_ctx.x is possibly 'undefined'
(TS18048)——修复方案在SFC模板或props中;详见references/error-playbook.md。

Audit & Hardening

审计与强化

For "audit the TypeScript setup" or "tighten types" on a project that already checks green:
  1. Setup:
    typescript
    pinned in devDependencies; a
    typecheck
    script in package.json; CI runs it. "Pinned" here means at least a caret major-compatible range (
    ^6.0.3
    ) 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 every
    typecheck*
    script, not just
    typecheck
    : match each against the CI workflow and report any (e.g. a native
    typecheck:ts7
    ) that CI never runs.
    inspect_typescript.py
    lists the native compiler and each script's target tsconfig.
  2. Coverage: every
    .ts
    /
    .tsx
    /
    .vue
    file falls inside some tsconfig's
    include
    (inspect_typescript.py reports uncovered files) — uncovered code is never type-checked.
  3. Effective strictness: read effective flags from the inspect output; framework-generated configs may set flags the root config does not show.
  4. Hygiene grep:
    : any
    ,
    as any
    ,
    @ts-ignore
    ,
    @ts-expect-error
    , and non-null assertions (the postfix
    x!
    operator). 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.
  5. Enable missing strictness flags one at a time, cheapest first (order above), fixing fallout per flag.
Linter rules (
no-explicit-any
and friends) are the linter's domain, not this skill's: note them in audit findings, fix them via lint config.
针对“审计TypeScript配置”或“收紧类型”的已正常检查项目:
  1. 基础设置:
    typescript
    在devDependencies中固定版本;package.json中有
    typecheck
    脚本;CI会运行该脚本。此处的“固定”指至少使用兼容主版本的脱字符范围(
    ^6.0.3
    )并提交lockfile;当编译器补丁曾导致构建失败时,优先使用兼容次版本的波浪号范围(
    ~6.0.3
    )或精确固定版本(
    6.0.3
    )。在并行编译器设置中,审计所有
    typecheck*
    脚本,而非仅
    typecheck
    :将每个脚本与CI工作流匹配,并报告任何CI从未运行的脚本(如原生的
    typecheck:ts7
    )。
    inspect_typescript.py
    会列出原生编译器及每个脚本的目标tsconfig。
  2. 覆盖范围:每个
    .ts
    /
    .tsx
    /
    .vue
    文件都被某个tsconfig的
    include
    覆盖(inspect_typescript.py会报告未被覆盖的文件)——未被覆盖的代码永远不会被类型检查。
  3. 有效严格性:从检查输出中读取有效标志;框架生成的配置可能设置了根配置未显示的标志。
  4. 卫生检查:搜索
    : any
    、
    as any
    、
    @ts-ignore
    、
    @ts-expect-error
    以及非空断言(后缀
    x!
    操作符)。优先处理导出/公共API和组件props > 服务器边界 > 内部工具。用真实的类型守卫或类型谓词替换断言;当每个调用站点都传递某个props时,将其设为必填而非可选。
  5. 按成本从低到高的顺序(如上所述)一次启用一个缺失的严格性标志,并针对每个标志修复问题。
检查器规则(
no-explicit-any
等)属于检查器的范畴,而非本技能:在审计结果中提及它们,通过检查器配置进行修复。

Error Playbook (quick)

错误手册(速查)

Full catalog with causes and prioritized fixes: references/error-playbook.md.
ErrorFirst move
TS2307 Cannot find moduleCheck
moduleResolution
matches how the code is run/bundled; then missing
@types
or
exports
map
TS2742 The inferred type cannot be namedExport the referenced type explicitly or annotate the declaration's return type
TS2589 Type instantiation is excessively deepBreak the recursion: simplify generic constraints, split unions, alias intermediate types
Excessive stack depth comparing typesReplace large type intersections with
interface extends
; limit recursive conditional types
TS5101 'baseUrl' is deprecatedDelete
baseUrl
; rewrite
paths
relative to the tsconfig (
"@/*": ["./src/*"]
) —
ignoreDeprecations
often masks exactly this
TypeScript 7 rejects a deprecated compiler optionUpgrade through TypeScript 6, remove
ignoreDeprecations
, and replace the option; see references/typescript-7-migration.md
TypeScript 7 reports missing Node/test globalsSet
compilerOptions.types
explicitly, for example
["node", "jest"]
; TypeScript 7 inherits TypeScript 6's empty default
A framework checker or tool fails after installing TypeScript 7Check its TypeScript peer range and compiler-API dependency; keep TypeScript 6 side by side when the tool has not added TypeScript 7 support
__VLS_ctx.x
is possibly 'undefined' (TS18048)
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
node_modules/typescript
包含原因和优先修复方案的完整目录:references/error-playbook.md。
错误第一步操作
TS2307 Cannot find module检查
moduleResolution
是否与代码运行/打包方式匹配;然后检查是否缺少
@types
或
exports
映射
TS2742 The inferred type cannot be named显式导出引用的类型,或为声明的返回类型添加注解
TS2589 Type instantiation is excessively deep打破递归:简化泛型约束、拆分联合类型、为中间类型设置别名
类型比较时栈溢出用
interface extends
替换大型类型交集;限制递归条件类型
TS5101 'baseUrl' is deprecated删除
baseUrl
;将
paths
重写为相对于tsconfig的路径(
"@/*": ["./src/*"]
)——
ignoreDeprecations
通常会掩盖这个问题
TypeScript 7拒绝已弃用的编译器选项先升级至TypeScript 6,移除
ignoreDeprecations
,然后替换该选项;详见references/typescript-7-migration.md
TypeScript 7报告缺少Node/测试全局变量显式设置
compilerOptions.types
,例如
["node", "jest"]
;TypeScript 7继承了TypeScript 6的空默认值
安装TypeScript 7后框架检查器或工具失败检查其TypeScript peer依赖范围和编译器API依赖;当工具尚未支持TypeScript 7时,保持TypeScript 6并行存在
__VLS_ctx.x
is possibly 'undefined' (TS18048)
Vue SFC中的模板错误:将props设为必填或设置默认值,或在模板中添加守卫
编辑器显示的错误与CLI不一致(或反之)比较TypeScript版本:编辑器内置的TS与工作区
node_modules/typescript
中的版本

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 trace
Reading the result: high
instantiations
or
check_time
dominating
total_time
means type-level complexity (heavy generics, huge unions, deep conditional types) — fix the types. High
files
/
lines
with modest check time means the program is too large — fix
include
/
exclude
, add project references, check that
node_modules
or generated output is not being picked up.
Standard remedies in order: precise
include
/
exclude
->
skipLibCheck
->
incremental
-> project references for multi-package repos.
当类型检查或编辑器运行缓慢时:
bash
python <skill>/scripts/trace_perf.py --root .
python <skill>/scripts/trace_perf.py --root . --trace   # 更深入:生成编译器跟踪日志
解读结果:
instantiations
或
check_time
占
total_time
比例过高意味着类型层面复杂度高(复杂泛型、大型联合类型、深层条件类型)——需要优化类型。
files
/
lines
数量多但检查时间适中意味着程序过大——需要优化
include
/
exclude
、添加项目引用、检查是否误包含了
node_modules
或生成的输出文件。
标准优化方案按顺序:精确设置
include
/
exclude
-> 启用
skipLibCheck
-> 启用
incremental
-> 为多包仓库添加项目引用。

Common Failure Modes

常见失败模式

  • paths
    aliases fail at runtime
    : tsconfig
    paths
    are compile-time only; the bundler or runtime needs its own alias config. See references/module-resolution.md.
  • Conflicting
    @types
    versions
    : duplicate
    @types/node
    (or react) across the tree; align versions or set
    compilerOptions.types
    explicitly.
  • Stale build state: delete
    .tsbuildinfo
    (and
    node_modules/.cache
    ) after config changes that should have changed the output but seemingly did not.
  • Editor vs CLI disagree: different TypeScript versions; point the editor to the workspace version.
  • ESM/CJS mixing:
    require
    of an ESM-only package or default-import mismatch; see references/module-resolution.md interop table.
  • Monorepo edits not picked up: project references need
    composite: true
    and a build step (
    tsc -b
    ); see references/monorepo.md.
  • paths
    别名在运行时失效
    :tsconfig的
    paths
    仅在编译时生效;打包器或运行时需要单独的别名配置。详见references/module-resolution.md。
  • @types
    版本冲突
    :树中存在重复的
    @types/node
    (或react);统一版本或显式设置
    compilerOptions.types
    。
  • 构建状态过时:在配置更改后,若输出未按预期变化,删除
    .tsbuildinfo
    (及
    node_modules/.cache
    )。
  • 编辑器与CLI结果不一致:TypeScript版本不同;将编辑器指向工作区版本。
  • ESM/CJS混合使用:
    require
    ESM-only包或默认导入不匹配;详见references/module-resolution.md中的互操作表。
  • Monorepo修改未被识别:项目引用需要
    composite: true
    及构建步骤(
    tsc -b
    );详见references/monorepo.md。

Reference Files

参考文件

  • references/error-playbook.md
    - Cryptic compiler errors: cause and prioritized fixes
  • references/module-resolution.md
    - module/moduleResolution pairs, ESM/CJS interop, paths, exports maps
  • references/migration.md
    - Incremental JavaScript-to-TypeScript migration
  • references/typescript-7-migration.md
    - Compiler migration to TypeScript 7, including TypeScript 6 compatibility and framework constraints
  • references/monorepo.md
    - Project references, composite builds, workspace typecheck order
  • references/error-playbook.md
    - 晦涩编译器错误:原因及优先修复方案
  • references/module-resolution.md
    - module/moduleResolution配对、ESM/CJS互操作、paths、exports映射
  • references/migration.md
    - JavaScript至TypeScript的增量迁移
  • references/typescript-7-migration.md
    - 迁移至TypeScript 7的编译器指南,包括TypeScript 6兼容性及框架约束
  • references/monorepo.md
    - 项目引用、复合构建、工作区类型检查顺序