Skill站外收录 @skilllib/skill-2117939930272414359
typescript-rules
确保 TypeScript 代码的类型安全与健壮性,通过类型守卫处理外部输入,在各层间明确区分未知类型与可信类型。禁止使用 any,优先以函数和接口实现逻辑,仅在必要时使用类。统一采用 async await 处理异步操作并配合 try catch 进行错误捕获,所有错误必须记录日志且不得静默失败。通过 Result 类型显式表达可能的错误,结合自定义错误类实现分层异常处理。严格保护敏感信息不被记
测试与安全 AI 技能
Skills.MD
# TypeScript Development Rules
## Type Safety in Backend Implementation
**Type Safety in Data Flow**
Input Layer (`unknown`) -> Type Guard -> Business Layer (Type Guaranteed) -> Output Layer (Serialization)
**Backend-Specific Type Scenarios**:
- **API Communication**: Always receive responses as `unknown`, validate with type guards
- **Form Input**: External input as `unknown`, type determined after validation
- **Legacy Integration**: Stepwise assertion like `window as unknown as LegacyWindow`
- **Test Code**: Always define types for mocks, utilize `Partial<T>` and `vi.fn<[Args], Return>()`
## Coding Conventions
**Class Usage Criteria**
- **Recommended: Implementation with Functions and Interfaces**
- Rationale: Improves testability and flexibility of function composition
- **Classes Allowed**:
- Framework requirements (NestJS Controller/Service, TypeORM Entity, etc.)
- Custom error class definitions
- When state and business logic are tightly coupled (e.g., ShoppingCart, Session, StateMachine)
- **Decision Criterion**: If "Does this data have behavior?" is Yes, consider using a class
```typescript
// Functions and interfaces
interface UserService { create(data: UserData): User }
const userService: UserService = { create: (data) => {...} }
```
**Function Design**
- **0-2 parameters maximum**: Use object for 3+ parameters
```typescript
// Object parameter
function createUser({ name, email, role }: CreateUserParams) {}
```
**Dependency Injection**
- **Inject external dependencies as parameters**: Ensure testability and modularity
```typescript
// Receive dependency as parameter
function createService(repository: Repository) { return {...} }
```
**Asynchronous Processing**
- Promise Handling: Always use `async/await`
- Error Handling: Always handle with `try-catch`
- Type Definition: Explicitly define return value types (e.g., `Promise<Result>`)
**Format Rules**
- Semicolon omission (follow Biome settings)
- Types in `PascalCase`, variables/functions in `camelCase`
- Imports use absolute paths (`src/`)
**Clean Code Principles**
- Delete unused code immediately
- Delete debug `console.log()`
- No commented-out code (manage history with version control)
- Comments explain "why" (not "what")
## Error Handling
**Absolute Rule**: Error suppression prohibited. All errors must have log output and appropriate handling.
**Fail-Fast Principle**: Fail quickly on errors to prevent continued processing in invalid states
```typescript
// Prohibited: Unconditional fallback
catch (error) {
return defaultValue // Hides error
}
// Required: Explicit failure
catch (error) {
logger.error('Processing failed', error)
throw error // Handle appropriately at higher layer
}
```
**Result Type Pattern**: Express errors with types for explicit handling
```typescript
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E }
// Example: Express error possibility with types
function parseUser(data: unknown): Result<User, ValidationError> {
if (!isValid(data)) return { ok: false, error: new ValidationError() }
return { ok: true, value: data as User }
}
```
**Custom Error Classes**
```typescript
export class AppError extends Error {
constructor(message: string, public readonly code: string, public readonly statusCode = 500) {
super(message)
this.name = this.constructor.name
}
}
// Purpose-specific: ValidationError(400), BusinessRuleError(400), DatabaseError(500), ExternalServiceError(502)
```
**Layer-Specific Error Handling (Backend)**
- API Layer: Convert to HTTP response, log output excluding sensitive information
- Service Layer: Detect business rule violations, propagate AppError as-is
- Repository Layer: Convert technical errors to domain errors
**Structured Logging and Sensitive Information Protection**
Never include sensitive information (password, token, apiKey, secret, creditCard) in logs
**Asynchronous Error Handling**
- Global handler setup mandatory: `unhandledRejection`, `uncaughtException`
- Use try-catch with all async/await
- Always log and re-throw errors
## Performance Optimization
- Streaming Processing: Process large datasets with streams
- Memory Leak Prevention: Explicitly release unnecessary objects
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「typescript-rules」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次