Advanced TypeScript Patterns for Better Code
Đang cập nhật
2 phút đọc
# Advanced TypeScript Patterns
TypeScript offers powerful features that go beyond basic type annotations. Let's explore advanced patterns that can make your code more robust and maintainable.
## Generic Constraints
```typescript interface Identifiable { id: string; }
function updateEntity<T extends Identifiable>( entity: T, updates: Partial<T> ): T { return { ...entity, ...updates }; } ```
## Conditional Types
```typescript type ApiResponse<T> = T extends string ? { message: T } : { data: T };
// Usage type StringResponse = ApiResponse<string>; // { message: string } type UserResponse = ApiResponse<User>; // { data: User } ```
## Utility Types
```typescript // Pick specific properties type UserSummary = Pick<User, 'id' | 'name' | 'email'>;
// Make all properties optional type PartialUser = Partial<User>;
// Make all properties required type RequiredUser = Required<User>; ```
## Template Literal Types
```typescript type EventName = `on${Capitalize<string>}`; type ClickEvent = `click${string}`;
// Usage const eventName: EventName = 'onClick'; // ✅ const clickEvent: ClickEvent = 'clickButton'; // ✅ ```
These patterns help create more expressive and type-safe APIs.
Bình luận
0Hãy là người đầu tiên bình luận.