|
21 | 21 | 3. **Union Types・Intersection Types**: Combinations of multiple types
|
22 | 22 | 4. **Type Assertions (Last Resort)**: Only when type is certain
|
23 | 23 |
|
| 24 | +**Type Guard Implementation Pattern** |
| 25 | +```typescript |
| 26 | +// Safely validate external input |
| 27 | +function isUser(value: unknown): value is User { |
| 28 | + return typeof value === 'object' && value !== null && |
| 29 | + 'id' in value && 'name' in value |
| 30 | +} |
| 31 | +// Usage: if (isUser(data)) { /* data is typed as User */ } |
| 32 | +``` |
| 33 | + |
24 | 34 | **Modern Type Features**
|
25 | 35 | - **satisfies Operator**: Type check while preserving type inference
|
26 | 36 | ```typescript
|
|
54 | 64 | Input Layer (`unknown`) → Type Guard → Business Layer (Type Guaranteed) → Output Layer (Serialization)
|
55 | 65 |
|
56 | 66 | **Type Complexity Management**
|
57 |
| -- Field Count: Up to 20 (split by responsibility if exceeded) |
| 67 | +- Field Count: Up to 20 (split by responsibility if exceeded, external API types are exceptions) |
58 | 68 | - Optional Ratio: Up to 30% (separate required/optional if exceeded)
|
59 | 69 | - Nesting Depth: Up to 3 levels (flatten if exceeded)
|
60 | 70 | - Type Assertions: Review design if used 3+ times
|
| 71 | +- **External API Types**: Relax constraints and define according to reality (convert appropriately internally) |
61 | 72 |
|
62 | 73 | ## Coding Conventions
|
63 | 74 |
|
64 | 75 | **Class Usage Criteria**
|
| 76 | +- **Recommended: Implementation with Functions and Interfaces** |
| 77 | + - Rationale: Improves testability and flexibility of function composition |
65 | 78 | - **Classes Allowed**:
|
66 | 79 | - Framework requirements (NestJS Controller/Service, TypeORM Entity, etc.)
|
67 | 80 | - Custom error class definitions
|
68 |
| -- **Classes Prohibited**: Use functions and interfaces for everything else |
| 81 | + - When state and business logic are tightly coupled (e.g., ShoppingCart, Session, StateMachine) |
| 82 | +- **Decision Criterion**: If "Does this data have behavior?" is Yes, consider using a class |
69 | 83 | ```typescript
|
70 | 84 | // ✅ Functions and interfaces
|
71 | 85 | interface UserService { create(data: UserData): User }
|
|
0 commit comments