TypeScript
Provide best-practice coding conventions and generate standards-compliant TypeScript code.
安装 / 下载方式
TotalClaw CLI推荐
totalclaw install skilldb:wscats~typescript-skillscURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/skilldb%3Awscats~typescript-skills/file -o typescript-skills.mdGit 仓库获取源码
git clone https://github.com/openclaw/skills/commit/7e0733997ed699f24d32638a01ac8bad1d36f22a# TypeScript Style Guide Skill
> **Activation**: This skill activates whenever the user says or implies **TypeScript**. It responds
> with standards-compliant TypeScript code and can explain any rule on demand.
---
## Table of Contents
1. [General Principles](#1-general-principles)
2. [Naming Conventions](#2-naming-conventions)
3. [Types & Interfaces](#3-types--interfaces)
4. [Enums](#4-enums)
5. [Variables & Constants](#5-variables--constants)
6. [Functions](#6-functions)
7. [Classes](#7-classes)
8. [Modules & Imports](#8-modules--imports)
9. [Generics](#9-generics)
10. [Error Handling](#10-error-handling)
11. [Async / Await & Promises](#11-async--await--promises)
12. [Comments & Documentation](#12-comments--documentation)
13. [Formatting & Style](#13-formatting--style)
14. [Null & Undefined Handling](#14-null--undefined-handling)
15. [Type Assertions & Guards](#15-type-assertions--guards)
16. [React & JSX (when applicable)](#16-react--jsx-when-applicable)
17. [Testing Conventions](#17-testing-conventions)
18. [Tooling & Configuration](#18-tooling--configuration)
---
## 1. General Principles
- **Strict mode always**: Enable `"strict": true` in `tsconfig.json`. This turns on `noImplicitAny`,
`strictNullChecks`, `strictFunctionTypes`, and more.
- **Prefer readability over cleverness**: Code is read far more often than written. Favour explicit,
self-documenting code.
- **Minimise `any`**: Treat every use of `any` as tech debt. Prefer `unknown` when the type is
truly not known, or use generics.
- **Immutability by default**: Use `const` over `let`; prefer `readonly` properties and
`ReadonlyArray<T>` / `Readonly<T>` utility types.
- **Single responsibility**: Each file, class, and function should have one clear purpose.
- **Keep files small**: A file should ideally stay under 400 lines. If it grows larger, consider
splitting it.
---
## 2. Naming Conventions
| Construct | Convention | Example |
| ----------------------- | ----------------------- | -------------------------------- |
| **Variable / Function** | `camelCase` | `getUserName`, `isActive` |
| **Boolean variable** | `camelCase` with prefix | `isLoading`, `hasAccess`, `canEdit` |
| **Constant (module)** | `UPPER_SNAKE_CASE` | `MAX_RETRY_COUNT`, `API_BASE_URL`|
| **Constant (local)** | `camelCase` | `const defaultTimeout = 3000` |
| **Class** | `PascalCase` | `UserService`, `HttpClient` |
| **Interface** | `PascalCase` | `UserProfile`, `ApiResponse` |
| **Type alias** | `PascalCase` | `UserId`, `Theme` |
| **Enum** | `PascalCase` | `Direction`, `HttpStatus` |
| **Enum member** | `PascalCase` | `Direction.Up`, `HttpStatus.Ok` |
| **Generic parameter** | Single uppercase letter or descriptive `PascalCase` | `T`, `TKey`, `TValue` |
| **File name** | `kebab-case.ts` | `user-service.ts`, `api-client.ts`|
| **Test file name** | `kebab-case.test.ts` or `kebab-case.spec.ts` | `user-service.test.ts` |
| **React component file**| `PascalCase.tsx` | `UserProfile.tsx` |
| **Private field** | `camelCase` (no `_` prefix) | `private count: number` |
### Additional Naming Rules
- **Do NOT** prefix interfaces with `I` (e.g., ~~`IUser`~~ → `User`).
- **Do NOT** suffix types/interfaces with `Type` or `Interface`.
- Use descriptive names. Avoid single-letter variables except for conventional usages like loop
indices (`i`, `j`) or generic type parameters (`T`, `K`, `V`).
- Acronyms of 2 characters stay uppercase (`IO`, `ID`); 3+ characters use PascalCase
(`Http`, `Xml`, `Api`).
---
## 3. Types & Interfaces
### Prefer `interface` for Object Shapes
```typescript
// ✅ Good — use interface for object shapes
interface User {
readonly id: string;
name: string;
email: string;
}
// ✅ Good — use type for unions, intersections, mapped types
type Status = 'active' | 'inactive' | 'suspended';
type Result<T> = Success<T> | Failure;
```
### When to Use `type` vs `interface`
| Use `interface` when … | Use `type` when … |
| ---------------------------------------------- | ------------------------------------------ |
| Defining the shape of an object or class | Creating union or intersection types |
| You want declaration merging | Using mapped / conditional types |
| Extending other interfaces | Aliasing primitive or tuple types |
### Rules
- Always annotate function return types explicitly for public APIs.
- Let TypeScript infer types for local variables when the type is obvious.
- Prefer `type` over `interface` for function signatures:
```typescript
type Comparator<T> = (a: T, b: T) => number;
```
- Avoid empty interfaces. If extending, include at least a comment explaining intent.
- Use `Record<K, V>` instead of `{ [key: string]: V }`.
- Use utility types (`Partial<T>`, `Pick<T, K>`, `Omit<T, K>`, `Required<T>`) to derive types
rather than duplicating.
---
## 4. Enums
### Prefer String Enums
```typescript
// ✅ Good — string enum for readability and debuggability
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT',
}
```
### When to Use `const` Enum or Union Types
```typescript
// ✅ Good — const enum for zero-runtime-cost enums (no reverse mapping needed)
const enum HttpMethod {
Get = 'GET',
Post = 'POST',
Put = 'PUT',
Delete = 'DELETE',
}
// ✅ Also good — string literal union (simpler, tree-shakeable)
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
```
### Rules
- **Do NOT** use numeric enums without explicit values (auto-increment is fragile).
- Prefer **string literal union types** over enums when the set is small and no namespace features
are needed.
- Never mix string and numeric members in the same enum.
---
## 5. Variables & Constants
```typescript
// ✅ Good
const maxRetries = 3;
const baseUrl = 'https://api.example.com';
let currentAttempt = 0;
// ❌ Bad — using var
var legacyValue = 'old';
// ❌ Bad — using let when value never changes
let neverReassigned = 42;
```
### Rules
- **Always use `const`** unless the variable needs reassignment; then use `let`.
- **Never use `var`**.
- Declare variables as close to their first usage as possible.
- One variable declaration per statement.
- Prefer destructuring for extracting properties:
```typescript
// ✅ Good
const { name, age } = user;
// ❌ Bad
const name = user.name;
const age = user.age;
```
- Use `as const` for immutable literal objects / arrays:
```typescript
const ROUTES = {
home: '/',
about: '/about',
contact: '/contact',
} as const;
```
---
## 6. Functions
### Function Declarations
```typescript
// ✅ Good — explicit return type for public functions
function calculateTotal(items: CartItem[]): number {
return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
// ✅ Good — arrow function for callbacks / short lambdas
const double = (n: number): number => n * 2;
// ✅ Good — use default parameters instead of optional + fallback
function createUser(name: string, role: Role = Role.Viewer): User {
// ...
}
```
### Rules
- **Annotate return types** for all exported / public functions.
- Prefer **arrow functions** for callbacks and inline functions.
- Prefer **function declarations** for top-level named functions (they are hoisted and more
readable in stack traces).
- **Maximum parameters**: 3. If more are needed, group them into an options object:
```typescript
// ✅ Good
interface CreateUserOptions {
name: string;
email: string;
role?: Role;
department?: string;
}
function createUser(options: CreateUserOptions): User { ... }
// ❌ Bad — too many positional parameters
func