AgentSkillsCN

typescript-best-practices

TypeScript/Node.js 编程的最佳实践。当用户编写或审查 TypeScript 代码时,可使用此技能。涵盖类型安全、异步编程模式以及错误处理的最佳实践。

SKILL.md
--- frontmatter
name: typescript-best-practices
description: TypeScript/Node.js best practices. Use when writing or reviewing TypeScript code. Covers type safety, async patterns, and error handling.
license: MIT
metadata:
  author: plan-cascade
  version: "1.0.0"

TypeScript Best Practices

Code Style

RuleGuideline
FormatterPrettier
LinterESLint + @typescript-eslint
Strict modestrict: true in tsconfig

Type Safety

RuleGuideline
Avoid anyUse unknown + narrowing
Type guardsCustom predicates
Discriminated unionsFor variants
typescript
type Result<T> = { success: true; data: T } | { success: false; error: Error };

function isUser(v: unknown): v is User {
  return typeof v === 'object' && v !== null && 'id' in v;
}

Error Handling

typescript
class ApiError extends Error {
  constructor(message: string, public status: number) {
    super(message);
    this.name = 'ApiError';
  }
}

async function fetchUser(id: string): Promise<User> {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new ApiError('Failed', res.status);
  return res.json();
}

Project Structure

code
src/{index.ts, types/, services/, utils/}
tests/
package.json, tsconfig.json

Async Patterns

PatternUsage
Promise.allParallel operations
AbortControllerCancellation
typescript
const [user, settings] = await Promise.all([fetchUser(id), fetchSettings(id)]);

Anti-Patterns

AvoidUse Instead
as assertionsType guards
! non-null?. and ??
anyunknown + narrowing
typescript
// Bad: data as User, user!.name
// Good:
if (isUser(data)) { /* data is User */ }
const name = user?.name ?? 'Unknown';

Testing (Vitest)

typescript
describe('Service', () => {
  it('should create', async () => {
    const mock = { save: vi.fn().mockResolvedValue({ id: '1' }) };
    const result = await new Service(mock).create({ name: 'Test' });
    expect(result.id).toBe('1');
  });
});