typescript-javascript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript & JavaScript Development
TypeScript & JavaScript 开发规范
Guiding Principles
指导原则
- Type Safety: Leverage strict mode, avoid , use discriminated unions
any - Explicit Over Implicit: Prefer explicit types for clarity and maintainability
- Modern Defaults: ESM, const/let, async/await, optional chaining
- Security First: Never use , sanitize HTML, validate inputs
eval
- 类型安全:启用严格模式,避免使用,使用可区分联合类型
any - 显式优于隐式:优先使用显式类型以提升清晰度和可维护性
- 现代默认规范:ESM、const/let、async/await、可选链
- 安全优先:绝不使用,清理HTML,验证输入
eval
Quick Reference
速查指南
| Aspect | TypeScript | JavaScript |
|---|---|---|
| Package Manager | | |
| Module System | ES Modules | ES Modules + |
| Linting | | |
| Formatting | Prettier | Prettier |
| Types | Strict mode | JSDoc types |
| 方面 | TypeScript | JavaScript |
|---|---|---|
| 包管理器 | 优先使用 | 优先使用 |
| 模块系统 | ES Modules | ES Modules + |
| 代码检查 | | |
| 代码格式化 | Prettier | Prettier |
| 类型处理 | 严格模式 | 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避免使用any
- 使用合适的类型
anytypescript
// ❌ 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>; // Immutabletypescript
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>; // ImmutableAsync 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, or unsanitizednew FunctioninnerHTML - Use for DOM insertion
textContent - 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 FunctioninnerHTML - 使用进行DOM插入
textContent - 验证并清理所有外部输入
- 不要记录密钥/令牌/个人身份信息(PII)
- 使用参数化查询;禁止拼接字符串查询
- 强制使用HTTPS;使用安全Cookie(HttpOnly、SameSite)
Naming Conventions
命名规范
| Type | Convention | Example |
|---|---|---|
| Functions/Variables | camelCase | |
| Classes/Interfaces | PascalCase | |
| Constants | UPPER_SNAKE_CASE | |
| Types | PascalCase | |
| 类型 | 规范 | 示例 |
|---|---|---|
| 函数/变量 | 小驼峰式(camelCase) | |
| 类/接口 | 大驼峰式(PascalCase) | |
| 常量 | 大写蛇形命名(UPPER_SNAKE_CASE) | |
| 类型 | 大驼峰式(PascalCase) | |
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