1. Type Safety and Modern TypeScript
Implement comprehensive type safety and modern TypeScript patterns for better code reliability and maintainability. This approach ensures better type checking and takes advantage of TypeScript's advanced type system.
// Type definitions
type UserRole = 'admin' | 'user' | 'guest';
interface UserPreferences {
theme: 'light' | 'dark';
notifications: boolean;
}
interface User {
id: string;
name: string;
email: string;
role: UserRole;
createdAt: Date;
preferences?: UserPreferences;
}
// Generic type utility
type ApiResponse = {
data: T;
status: number;
message: string;
};
// Type-safe service
class UserService {
private apiUrl: string;
constructor(apiUrl: string) {
this.apiUrl = apiUrl;
}
async getUser(userId: string): Promise> {
try {
// Simulated API call
const userData: User = {
id: userId,
name: 'John Doe',
email: '[email protected]',
role: 'user',
createdAt: new Date(),
preferences: {
theme: 'dark',
notifications: true
}
};
return {
data: userData,
status: 200,
message: 'User retrieved successfully'
};
} catch (error) {
throw new Error(`Failed to fetch user: ${error instanceof Error ? error.message : String(error)}`);
}
}
async updateUser(
userId: string,
updates: Partial
): Promise> {
try {
// Simulated API call
const userData: User = {
id: userId,
name: updates.name ?? 'John Doe',
email: updates.email ?? '[email protected]',
role: updates.role ?? 'user',
createdAt: new Date(),
preferences: updates.preferences ?? {
theme: 'dark',
notifications: true
}
};
return {
data: userData,
status: 200,
message: 'User updated successfully'
};
} catch (error) {
throw new Error(`Failed to update user: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
// Example usage
async function main() {
const userService = new UserService('https://api.example.com');
try {
// Get user
const response = await userService.getUser('123');
console.log('User:', response.data);
// Update user
const updates = {
name: 'Jane Doe',
role: 'admin' as UserRole
};
const updateResponse = await userService.updateUser('123', updates);
console.log('Updated user:', updateResponse.data);
} catch (error) {
console.error('Error:', error instanceof Error ? error.message : String(error));
}
}
// Run the example
main().catch(console.error);
Why This Rule Matters
- Enables better type safety and error prevention
- Improves code reliability and maintainability
- Facilitates better IDE support and autocompletion
- Reduces runtime errors
- Enables better code documentation
Using with Cursor
Cursor's AI capabilities can help you:
- Suggest type definitions
- Generate interfaces
- Implement generic types
- Improve type safety
- Fix type errors