关于 typescript
面向 TypeScript 开发的技能,提供严格类型检查与一致编码规范的实践指引,涵盖配置、类型设计、函数、泛型和工具类型。
主要功能
- 01严格的 TypeScript 配置
- 02命名规范
- 03type 与 interface 的用法
- 04用 unknown 避免 any
- 05工具类型与泛型
适用场景
- 01设置严格的 tsconfig.json 选项
- 02为对象结构和联合类型选择类型
- 03为公共函数和泛型添加类型
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ alicoder001/ agent-skills --skill typescript安装后在 Claude Code 中输入/typescript确认已加载。
附带文件agents/openai.yaml
详细介绍
TypeScript 专业开发
面向专业开发的严格 TypeScript 模式。
说明
1. 严格模式配置
始终在 tsconfig.json 中启用严格模式:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUnusedLocals": true,
"noUnusedParameters": true
}
}
2. 命名约定
| 类型 | 约定 | 示例 |
|---|---|---|
| 接口 | PascalCase,可选地添加 I 前缀 | User、IUserService |
| 类型 | PascalCase | UserRole、ApiResponse |
| 枚举 | PascalCase | Status、Direction |
| 函数 | camelCase | getUserById、calculateTotal |
| 变量 | camelCase | userName、isLoading |
| 常量 | UPPER_SNAKE_CASE | MAX_RETRY_COUNT、API_URL |
3. 类型与接口
// ✅ Interface for object shapes
interface User {
id: string;
name: string;
email: string;
}
// ✅ Type for unions, intersections, primitives
type Status = 'pending' | 'active' | 'inactive';
type ApiResponse<T> = { data: T; error: null } | { data: null; error: string };
4. 切勿使用 any
// ❌ Bad
function process(data: any) { ... }
// ✅ Good - use unknown and narrow
function process(data: unknown) {
if (typeof data === 'string') {
return data.toUpperCase();
}
}
// ✅ Good - use generics
function process<T>(data: T): T { ... }
5. 工具类型
// Partial - all optional
type PartialUser = Partial<User>;
// Required - all required
type RequiredUser = Required<User>;
// Pick - select specific
type UserName = Pick<User, 'name'>;
// Omit - exclude specific
type UserWithoutId = Omit<User, 'id'>;
// Record - key-value mapping
type UserMap = Record<string, User>;
6. 函数类型
// ✅ Explicit return types for public APIs
function getUser(id: string): Promise<User | null> {
// ...
}
// ✅ Arrow function with types
const add = (a: number, b: number): number => a + b;
7. 泛型
// ✅ Constrained generics
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// ✅ Default generic types
interface ApiResponse<T = unknown> {
data: T;
status: number;
}
参考资料
评论
支持 Markdown