mcpField
T
typescript-best-practices

typescript-best-practices

github.com/jwynia开发180603 次安装35 周前更新
代码仓库

关于 typescript-best-practices

typescript-best-practices 为编写和审查 TypeScript 的 Agent 提供编码规范、架构模式及辅助脚本。它涵盖类型安全、不可变性、错误处理与代码组织,也包含代码分析、类型生成和模块脚手架工具。

主要功能

  1. 01强调类型安全与不可变性
  2. 02提供错误处理和模块设计模式
  3. 03提供 TypeScript 代码分析脚本
  4. 04从 JSON 生成 TypeScript 类型
  5. 05脚手架创建结构化模块

适用场景

  1. 01生成新的 TypeScript 代码
  2. 02审查 TypeScript 文件的质量
  3. 03将 JavaScript 重构为 TypeScript
  4. 04创建模块、服务或组件

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jwynia/agent-skills --skill typescript-best-practices

安装后在 Claude Code 中输入/typescript-best-practices确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/templates/
module-template.ts.md
service-template.ts.md
assets/tsconfig-presets/
recommended.json
strict.json
references/anti-patterns/
common-mistakes.md
references/architecture/
api-design.md
project-structure.md
references/patterns/
async-patterns.md
error-handling.md
functional-patterns.md
module-patterns.md
references/type-system/
advanced-types.md
type-guards.md
utility-types.md
scripts/
analyze.ts
generate-types.ts
scaffold-module.ts

详细介绍

TypeScript 最佳实践

指导 AI Agent 编写高质量的 TypeScript 代码。此技能提供编码标准、架构模式以及用于分析和脚手架搭建的工具。

何时使用此技能

在以下情况下使用此技能:

  • 生成新的 TypeScript 代码
  • 检查 TypeScript 文件中的质量问题
  • 创建新的模块、服务或组件
  • 将 JavaScript 重构为 TypeScript
  • 解答有关 TypeScript 模式或类型的问题
  • 设计 API 或接口

在以下情况下不要使用此技能:

  • 处理纯 JavaScript(不含 TypeScript)
  • 调试运行时错误(使用调试工具)
  • 使用特定框架的模式(React、Vue 等;请使用相应的框架技能)

核心原则

1. 类型安全优先

尽可能多地在编译时检测错误:

// Prefer unknown over any for unknown types
function processInput(data: unknown): string {
  if (typeof data === "string") return data;
  if (typeof data === "number") return String(data);
  throw new Error("Unsupported type");
}

// Explicit return types for public APIs
export function calculateTotal(items: ReadonlyArray<Item>): number {
  return items.reduce((sum, item) => sum + item.price, 0);
}

// Use const assertions for literal types
const CONFIG = {
  mode: "production",
  version: 1,
} as const;
2. 默认不可变

防止意外修改:

// Use readonly for object properties
interface User {
  readonly id: string;
  readonly email: string;
  name: string; // Only mutable if intentional
}

// Use ReadonlyArray for collections
function processItems(items: ReadonlyArray<Item>): ReadonlyArray<Result> {
  return items.map(transform);
}

// Prefer spreading over mutation
function updateUser(user: User, name: string): User {
  return { ...user, name };
}
3. 使用类型处理错误

使用类型系统处理错误:

// Result type for recoverable errors
type Result<T, E = Error> =
  | { success: true; value: T }
  | { success: false; error: E };

// Typed error classes
class ValidationError extends Error {
  constructor(
    message: string,
    readonly field: string,
    readonly code: string
  ) {
    super(message);
    this.name = "ValidationError";
  }
}

// Function with Result return type
function parseConfig(input: string): Result<Config, ValidationError> {
  try {
    const data = JSON.parse(input);
    if (!isValidConfig(data)) {
      return {
        success: false,
        error: new ValidationError("Invalid config", "root", "INVALID_FORMAT"),
      };
    }
    return { success: true, value: data };
  } catch {
    return {
      success: false,
      error: new ValidationError("Parse failed", "root", "PARSE_ERROR"),
    };
  }
}
4. 代码组织

合理组织代码,便于维护:

// One concept per file
// user.ts - User type and related utilities
export interface User {
  readonly id: string;
  readonly email: string;
  readonly createdAt: Date;
}

export function createUser(email: string): User {
  return {
    id: crypto.randomUUID(),
    email,
    createdAt: new Date(),
  };
}

// Explicit exports (no barrel file wildcards)
// index.ts
export { User, createUser } from "./user.ts";
export { validateEmail } from "./validation.ts";

快速参考

类别优先使用避免使用
未知类型unknownany
集合ReadonlyArray<T>将 T[] 用作输入
对象Readonly<T>默认使用可变对象
空值检查可选链 ?.!= null
类型收窄类型守卫as 断言
返回类型为导出项显式声明为导出项推断
枚举字符串字面量联合类型数字枚举
导入命名导入默认导入
错误Result 类型通过抛出错误控制流程
循环for...of、.map()对数组使用 for...in

代码生成指南

生成 TypeScript 代码时,请遵循以下模式:

模块结构
/**
 * Module description
 * @module module-name
 */

// === Types ===
export interface ModuleOptions {
  readonly setting: string;
}

export interface ModuleResult {
  readonly data: unknown;
}

// === Constants ===
const DEFAULT_OPTIONS: ModuleOptions = {
  setting: "default",
};

// === Implementation ===
export function processData(
  input: unknown,
  options: Partial<ModuleOptions> = {}
): ModuleResult {
  const opts = { ...DEFAULT_OPTIONS, ...options };
  // Implementation
  return { data: input };
}
函数设计
// Pure functions preferred
function transform(input: Input): Output {
  // No side effects, same input = same output
  return { ...input, processed: true };
}

// Explicit parameter types
function fetchUser(id: string, options?: FetchOptions): Promise<User> {
  // Implementation
}

// Use function overloads for complex signatures
function parse(input: string): ParsedData;
function parse(input: Buffer): ParsedData;
function parse(input: string | Buffer): ParsedData {
  // Implementation
}
接口设计
// Prefer interfaces for object shapes
interface UserData {
  readonly id: string;
  readonly email: string;
}

// Use type for unions and intersections
type UserRole = "admin" | "user" | "guest";
type AdminUser = UserData & { readonly role: "admin" };

// Document with JSDoc
/**
 * Configuration for the API client
 * @property baseUrl - The base URL for API requests
 * @property timeout - Request timeout in milliseconds
 */
interface ApiConfig {
  readonly baseUrl: string;
  readonly timeout?: number;
}

常见反模式

生成代码时避免以下模式:

反模式问题解决方案
any 类型禁用类型检查使用 unknown 并收窄类型
as 断言可能导致运行时错误使用类型守卫
非空断言 !空指针错误使用可选链 ?.
可变参数意外修改使用 Readonly<T>
魔法字符串易出错且无自动补全使用字符串字面量类型
上帝类难以测试和维护遵循单一职责原则
循环依赖构建或运行时问题依赖倒置
索引签名丢失类型信息显式声明属性

详细示例请参阅 references/anti-patterns/common-mistakes.md。

脚本参考

analyze.ts

分析 TypeScript 代码中的质量问题:

deno run --allow-read scripts/analyze.ts <path> [options]

Options:
  --strict        Enable all checks
  --json          Output JSON for programmatic use
  --fix-hints     Show suggested fixes

Examples:
  # Analyze a file
  deno run --allow-read scripts/analyze.ts ./src/utils.ts

  # Analyze directory with strict mode
  deno run --allow-read scripts/analyze.ts ./src --strict

  # JSON output for CI
  deno run --allow-read scripts/analyze.ts ./src --json
generate-types.ts

根据 JSON 数据生成 TypeScript 类型:

deno run --allow-read --allow-write scripts/generate-types.ts <input> [options]

Options:
  --name <name>   Root type name (default: inferred)
  --output <path> Output file path
  --readonly      Generate readonly types
  --interface     Use interface instead of type

Examples:
  # Generate from JSON file
  deno run --allow-read scripts/generate-types.ts ./data.json --name Config

  # Generate readonly interface
  deno run --allow-read --allow-write scripts/generate-types.ts ./api-response.json \
    --interface --readonly --output ./types/api.ts
scaffold-module.ts

创建结构规范的 TypeScript 模块:

deno run --allow-read --allow-write scripts/scaffold-module.ts [options]

Options:
  --name <name>   Module name (required)
  --path <path>   Target directory (default: ./src)
  --type <type>   Type: service, util, component
  --with-tests    Include test file

Examples:
  # Create a utility module
  deno run --allow-read --allow-write scripts/scaffold-module.ts \
    --name "string-utils" --type util

  # Create a service with tests
  deno run --allow-read --allow-write scripts/scaffold-module.ts \
    --name "user-service" --type service --with-tests

更多资源

类型系统深入解析
  • references/type-system/advanced-types.md - 泛型、条件类型、映射类型
  • references/type-system/type-guards.md - 类型收窄技术
  • references/type-system/utility-types.md - 内置工具类型
模式指南
  • references/patterns/error-handling.md - Result 类型、类型化错误
  • references/patterns/async-patterns.md - Async/await 最佳实践
  • references/patterns/functional-patterns.md - 不可变性、组合
  • references/patterns/module-patterns.md - 导出、依赖注入
架构
  • references/architecture/project-structure.md - 目录组织
  • references/architecture/api-design.md - 接口设计、版本控制
模板
  • assets/templates/module-template.ts.md - 模块起始模板
  • assets/templates/service-template.ts.md - 服务类模板
  • assets/tsconfig-presets/strict.json - 最严格配置
  • assets/tsconfig-presets/recommended.json - 均衡的默认配置

评论

支持 Markdown