{
  "id": "ai-rules-for-typescript-strict-projects",
  "type": "rules",
  "category": "rules",
  "locale": "zh",
  "url": "/zh/rules/ai-rules-for-typescript-strict-projects",
  "title": "TypeScript严格模式项目的AI编码规则",
  "description": "适用于TypeScript严格模式项目的AGENTS.md规则，用于消除any类型、强制窄化模式，并防止代理生成编译通过但语义错误的代码。",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "TypeScript",
    "Next.js"
  ],
  "tags": [
    "agents-md",
    "typescript",
    "conventions",
    "security"
  ],
  "difficulty": null,
  "updated": "2026-06-08",
  "markdown": "将此文件放入仓库根目录命名为`AGENTS.md`。TypeScript严格模式的有效性取决于能否阻止代理使用`any`强制类型转换和`@ts-ignore`注释来绕过它。\n\n## AGENTS.md\n\n```md title=\"AGENTS.md\"\n# Project Rules — TypeScript Strict\n\n## TypeScript configuration\n- `strict: true` is set in `tsconfig.json`. This enables `noImplicitAny`,\n  `strictNullChecks`, `strictFunctionTypes`, `strictBindCallApply`,\n  `strictPropertyInitialization`, and `noImplicitThis`. Do not disable any of these.\n- `noUncheckedIndexedAccess: true` is enabled. Array indexing returns `T | undefined`.\n  Always check array access results before using them.\n- `exactOptionalPropertyTypes: true` is enabled. Do not assign `undefined` to an\n  optional property — omit the property instead.\n\n## Hard rules — no exceptions\n- NEVER use `any`. Use `unknown` for values of uncertain type and narrow them\n  before use. The single exception is third-party library types that are themselves\n  typed as `any` — wrap and re-export with a proper type.\n- NEVER use `as T` type assertions unless you add a comment explaining why the\n  compiler cannot infer the type and why the assertion is safe. Prefer type guards.\n- NEVER use `@ts-ignore` or `@ts-expect-error` without a comment on the same line\n  explaining the exact reason. If you find yourself using these, refactor instead.\n- NEVER use non-null assertion (`!`) on values that could genuinely be null/undefined\n  at runtime. Write an explicit check or use optional chaining (`?.`).\n- NEVER widen a type unnecessarily. If a function returns `string`, type it as\n  `string` — not `string | undefined` just to avoid a null check.\n\n## Type design conventions\n- Model domain errors with discriminated unions, not thrown errors or `null`.\n  Return `{ ok: true; value: T } | { ok: false; error: string }` from fallible\n  operations instead of relying on catch at the call site.\n- Prefer `type` aliases for unions and intersections; use `interface` for object\n  shapes that may be extended. Be consistent within a file.\n- Generic constraints should be as narrow as possible: `T extends string` instead of\n  `T extends unknown` when you only use string operations on `T`.\n- Export only what callers need. Keep internal implementation types unexported unless\n  there is an explicit reason to expose them.\n\n## Narrowing and runtime validation\n- All external data (API responses, form input, `JSON.parse` output, URL params) must\n  be validated at the boundary with Zod or a type guard before being used as a typed\n  value. Never cast external data with `as MyType` without validation.\n- Use `satisfies` to validate object literals against a type without widening:\n  `const config = { ... } satisfies Config` instead of `const config: Config = { ... }`\n  when you need to preserve literal types.\n- Exhaustiveness checks in `switch` statements: add a `default: assertNever(x)` arm\n  where `assertNever` is `(x: never) => never` — this catches unhandled union members\n  at compile time when the union is extended.\n\n## Definition of done\n- `tsc --noEmit` passes with zero errors.\n- `grep -r 'as any\\|: any\\|@ts-ignore\\|@ts-expect-error' src/` returns zero results\n  (or every hit has an approved justification comment).\n- ESLint with `@typescript-eslint/no-explicit-any` and `@typescript-eslint/no-unsafe-*`\n  rules enabled passes.\n- No `!` non-null assertions on values that come from external data or optional fields.\n```\n\n## 为何制定这些规则\n\n- **禁止无注释的`as T`** 是禁止`any`之后最重要的规则。类型断言是代理在不真正修复错误的情况下“修复”TypeScript错误的主要方式——代码可以编译，但运行时类型保证已丢失。要求提供书面理由，迫使代理思考断言是否真正安全。\n- **在边界处验证外部数据** 可防止TypeScript应用中最广泛的运行时类型错误。见到类型化API响应的代理通常信任类型注解，而不检查是否在获取时进行了验证，从而生成TypeScript类型是谎言的应用——编译毫无问题，但运行时却会意外崩溃。\n\n## 适用场景\n\n- 使用`strict: true`的生产级TypeScript代码库，其中类型安全是一流的质量要求——尤其是处理用户数据、金融交易或外部API集成的代码库。\n\n## 不适用场景\n\n- 快速原型开发或脚本，严格类型安全只会增加开销而无收益——对于一次性代码，应使用`strict: false`和更轻量的规则集。"
}