关于 typescript-best-practices
typescript-best-practices 为编写和审查 TypeScript 的 Agent 提供编码规范、架构模式及辅助脚本。它涵盖类型安全、不可变性、错误处理与代码组织,也包含代码分析、类型生成和模块脚手架工具。
主要功能
- 01强调类型安全与不可变性
- 02提供错误处理和模块设计模式
- 03提供 TypeScript 代码分析脚本
- 04从 JSON 生成 TypeScript 类型
- 05脚手架创建结构化模块
适用场景
- 01生成新的 TypeScript 代码
- 02审查 TypeScript 文件的质量
- 03将 JavaScript 重构为 TypeScript
- 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.mdservice-template.ts.mdassets/tsconfig-presets/recommended.jsonstrict.jsonreferences/anti-patterns/common-mistakes.mdreferences/architecture/api-design.mdproject-structure.mdreferences/patterns/async-patterns.mderror-handling.mdfunctional-patterns.mdmodule-patterns.mdreferences/type-system/advanced-types.mdtype-guards.mdutility-types.mdscripts/analyze.tsgenerate-types.tsscaffold-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";
快速参考
| 类别 | 优先使用 | 避免使用 |
|---|---|---|
| 未知类型 | unknown | any |
| 集合 | 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