typescript-javascript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript & JavaScript Development

TypeScript & JavaScript 开发规范

Guiding Principles

指导原则

  1. Type Safety: Leverage strict mode, avoid
    any
    , use discriminated unions
  2. Explicit Over Implicit: Prefer explicit types for clarity and maintainability
  3. Modern Defaults: ESM, const/let, async/await, optional chaining
  4. Security First: Never use
    eval
    , sanitize HTML, validate inputs
  1. 类型安全:启用严格模式,避免使用
    any
    ,使用可区分联合类型
  2. 显式优于隐式:优先使用显式类型以提升清晰度和可维护性
  3. 现代默认规范:ESM、const/let、async/await、可选链
  4. 安全优先:绝不使用
    eval
    ,清理HTML,验证输入

Quick Reference

速查指南

AspectTypeScriptJavaScript
Package Manager
pnpm
preferred
pnpm
preferred
Module SystemES ModulesES Modules +
// @ts-check
Linting
eslint --max-warnings=0
eslint --max-warnings=0
FormattingPrettierPrettier
TypesStrict modeJSDoc types
方面TypeScriptJavaScript
包管理器优先使用
pnpm
优先使用
pnpm
模块系统ES ModulesES Modules +
// @ts-check
代码检查
eslint --max-warnings=0
eslint --max-warnings=0
代码格式化PrettierPrettier
类型处理严格模式JSDoc类型

Critical Patterns

核心模式

typescript
// 1. Use strict equality
if (value === 0) { }        // ✅ GOOD
if (value == 0) { }         // ❌ BAD

// 2. Handle Promise rejections
fetchData().catch(err => console.error(err));  // ✅ GOOD

// 3. Optional chaining and nullish coalescing
const name = user?.profile?.name ?? 'Guest';  // ✅ GOOD

// 4. Use Set/Map for lookups
const seen = new Set();     // ✅ GOOD (O(1))
const seen = [];            // ❌ BAD (O(n))

// 5. Never use eval or new Function
eval(userInput);            // ❌ NEVER DO THIS

// 6. Sanitize HTML
element.textContent = userInput;  // ✅ GOOD
element.innerHTML = userInput;    // ❌ BAD (XSS)
typescript
// 1. Use strict equality
if (value === 0) { }        // ✅ GOOD
if (value == 0) { }         // ❌ BAD

// 2. Handle Promise rejections
fetchData().catch(err => console.error(err));  // ✅ GOOD

// 3. Optional chaining and nullish coalescing
const name = user?.profile?.name ?? 'Guest';  // ✅ GOOD

// 4. Use Set/Map for lookups
const seen = new Set();     // ✅ GOOD (O(1))
const seen = [];            // ❌ BAD (O(n))

// 5. Never use eval or new Function
eval(userInput);            // ❌ NEVER DO THIS

// 6. Sanitize HTML
element.textContent = userInput;  // ✅ GOOD
element.innerHTML = userInput;    // ❌ BAD (XSS)

TypeScript Configuration

TypeScript 配置

json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noUncheckedIndexedAccess": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}
json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noUncheckedIndexedAccess": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

Avoid
any
- Use Proper Types

避免使用
any
- 使用合适的类型

typescript
// ❌ BAD - Loses all type safety
function processData(data: any): any {
  return data.value;
}

// ✅ GOOD - Generic type
function processData<T>(data: T): T {
  return data;
}

// ✅ GOOD - Unknown for truly unknown types
function processData(data: unknown): string {
  if (typeof data === 'object' && data !== null && 'value' in data) {
    return String((data as { value: unknown }).value);
  }
  throw new Error('Invalid data');
}
typescript
// ❌ BAD - Loses all type safety
function processData(data: any): any {
  return data.value;
}

// ✅ GOOD - Generic type
function processData<T>(data: T): T {
  return data;
}

// ✅ GOOD - Unknown for truly unknown types
function processData(data: unknown): string {
  if (typeof data === 'object' && data !== null && 'value' in data) {
    return String((data as { value: unknown }).value);
  }
  throw new Error('Invalid data');
}

Discriminated Unions

可区分联合类型

typescript
type SuccessResponse = {
  status: 'success';
  data: { id: string; name: string };
};

type ErrorResponse = {
  status: 'error';
  error: { code: number; message: string };
};

type ApiResponse = SuccessResponse | ErrorResponse;

function handleResponse(response: ApiResponse): void {
  if (response.status === 'success') {
    console.log(response.data.id);  // Type-safe
  } else {
    console.log(response.error.message);  // Type-safe
  }
}
typescript
type SuccessResponse = {
  status: 'success';
  data: { id: string; name: string };
};

type ErrorResponse = {
  status: 'error';
  error: { code: number; message: string };
};

type ApiResponse = SuccessResponse | ErrorResponse;

function handleResponse(response: ApiResponse): void {
  if (response.status === 'success') {
    console.log(response.data.id);  // Type-safe
  } else {
    console.log(response.error.message);  // Type-safe
  }
}

Utility Types

工具类型

typescript
interface User {
  id: string;
  name: string;
  email: string;
  password: string;
}

type UserUpdate = Partial<User>;           // All optional
type UserCredentials = Pick<User, 'email' | 'password'>;
type UserPublic = Omit<User, 'password'>;  // Exclude password
type RequiredUser = Required<User>;        // All required
type ReadonlyUser = Readonly<User>;        // Immutable
typescript
interface User {
  id: string;
  name: string;
  email: string;
  password: string;
}

type UserUpdate = Partial<User>;           // All optional
type UserCredentials = Pick<User, 'email' | 'password'>;
type UserPublic = Omit<User, 'password'>;  // Exclude password
type RequiredUser = Required<User>;        // All required
type ReadonlyUser = Readonly<User>;        // Immutable

Async Patterns

异步模式

typescript
// Parallel execution
const [users, products] = await Promise.all([
  fetchUsers(),
  fetchProducts()
]);

// Handle partial failures
const results = await Promise.allSettled([
  fetchUsers(),
  fetchProducts()
]);

results.forEach(result => {
  if (result.status === 'fulfilled') {
    console.log(result.value);
  } else {
    console.error(result.reason);
  }
});
typescript
// Parallel execution
const [users, products] = await Promise.all([
  fetchUsers(),
  fetchProducts()
]);

// Handle partial failures
const results = await Promise.allSettled([
  fetchUsers(),
  fetchProducts()
]);

results.forEach(result => {
  if (result.status === 'fulfilled') {
    console.log(result.value);
  } else {
    console.error(result.reason);
  }
});

Security Rules (Mandatory)

安全规则(强制执行)

  • Never use
    eval
    ,
    new Function
    , or unsanitized
    innerHTML
  • Use
    textContent
    for DOM insertion
  • Validate and sanitize all external inputs
  • Do not log secrets/tokens/PII
  • Use parameterized queries; no string-built queries
  • Enforce HTTPS; secure cookies (HttpOnly, SameSite)
  • 绝不使用
    eval
    new Function
    或未清理的
    innerHTML
  • 使用
    textContent
    进行DOM插入
  • 验证并清理所有外部输入
  • 不要记录密钥/令牌/个人身份信息(PII)
  • 使用参数化查询;禁止拼接字符串查询
  • 强制使用HTTPS;使用安全Cookie(HttpOnly、SameSite)

Naming Conventions

命名规范

TypeConventionExample
Functions/VariablescamelCase
fetchUserData
Classes/InterfacesPascalCase
UserService
ConstantsUPPER_SNAKE_CASE
MAX_RETRIES
TypesPascalCase
ApiResponse
类型规范示例
函数/变量小驼峰式(camelCase)
fetchUserData
类/接口大驼峰式(PascalCase)
UserService
常量大写蛇形命名(UPPER_SNAKE_CASE)
MAX_RETRIES
类型大驼峰式(PascalCase)
ApiResponse

Detailed References

详细参考

  • TypeScript Patterns: See references/typescript-patterns.md for advanced types, generics, mapped types
  • JavaScript Patterns: See references/javascript-patterns.md for JSDoc, ESM, performance
  • TypeScript 模式:高级类型、泛型、映射类型请参考references/typescript-patterns.md
  • JavaScript 模式:JSDoc、ESM、性能相关内容请参考references/javascript-patterns.md