← 返回首页

typescript-strict@1.0.0

TypeScript 严格模式编码规范与类型安全最佳实践

CLI 安装指南

通过 SkillSPAI CLI 一键安装到你的 AI 编码工具:

1. 安装 CLI(如尚未安装)

npm install -g skillspai

2. 安装此 Skill 到目标平台

# Codex CLI
skillspai install typescript-strict --target codex

# Claude Code
skillspai install typescript-strict --target claude

# Cursor
skillspai install typescript-strict --target cursor

# Windsurf
skillspai install typescript-strict --target windsurf

# OpenCode
skillspai install typescript-strict --target opencode

3. 或指定版本安装

skillspai install typescript-strict@1.0.0 --target claude

Skill 内容

# TypeScript 严格模式编码规范

## 配置要求

```json
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "exactOptionalPropertyTypes": true,
    "forceConsistentCasingInFileNames": true
  }
}
```

## 类型定义

- 优先用 `interface` 定义对象类型,`type` 用于联合类型和工具类型
- 函数参数和返回值必须显式标注类型
- 不要用 `any`,用 `unknown` 替代,然后做类型守卫
- 用 `as const` 推断字面量类型
- 枚举用 `const enum` 或字符串联合类型替代普通枚举

## 类型安全

- 用 Zod 或 Valibot 做运行时校验,不要只信 TypeScript 类型
- API 响应用 Zod schema 解析,不要直接 `as Type`
- 用 `satisfies` 操作符检查类型兼容性
- 用模板字面量类型约束字符串格式(如路由路径)

## 泛型

- 泛型参数用有意义的名称(`TItem` 不要 `T`)
- 用 `extends` 约束泛型,不要在函数体里做类型断言
- 条件类型用 `infer` 提取,不要手动拆解

## 导入导出

- 用 named export,不要用 default export
- 导入顺序:内置模块 → 第三方 → 本地模块
- 类型导入用 `import type`,避免运行时引入类型代码
- barrel export(index.ts)只在模块边界使用,不要过度使用

## 常见错误

- 不要用 `!` 非空断言,用可选链 `?.` 和空值合并 `??`
- 不要用 `as` 类型断言,用类型守卫函数
- 不要忽略 Promise 返回值(用 `void` 显式标记)
- 不要用 `@ts-ignore`,用 `@ts-expect-error` 并说明原因