TypeScript Type System¶
This document explains the type system used in AiluroCamp and how we leverage TypeScript to create a type-safe application.
Overview¶
AiluroCamp uses TypeScript to provide static type checking, improving code quality and developer experience. Our type system is designed to:
- Ensure consistency across the application
- Prevent common runtime errors
- Provide better IDE support with autocompletion
- Document the expected shape of data
- Make refactoring safer and easier
Types Folder Structure¶
The src/app/types directory contains all shared TypeScript interfaces and type definitions used throughout the application. This centralized approach ensures consistency and makes it easier to maintain and update types as the application evolves.
Key Type Definitions¶
User Types (src/app/types/user.ts)¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
These types define:
- The structure of a user object
- The possible user roles as a union type
- Request and response formats for user-related API calls
Authentication Types¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
These types extend the NextAuth.js types to include our custom properties like roles and currentRole.
Using Types in the Application¶
In React Components¶
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
In API Routes¶
1 2 3 4 5 6 7 8 9 | |
Type Safety Best Practices¶
1. Use Explicit Return Types¶
Always specify return types for functions, especially for async functions:
1 2 3 | |
2. Use Type Guards¶
Use type guards to narrow types when necessary:
1 2 3 4 5 6 7 | |
3. Avoid any¶
Avoid using the any type as it defeats the purpose of TypeScript. Use unknown instead when the type is truly not known, then narrow it down:
1 2 3 4 5 6 7 8 9 10 11 | |
4. Use Discriminated Unions¶
For complex state management, use discriminated unions:
1 2 3 4 5 | |
5. Leverage Generics¶
Use generics for reusable components and functions:
1 2 3 4 5 6 7 | |
MongoDB and Mongoose Types¶
We use Mongoose with TypeScript to ensure type safety with our database operations:
1 2 3 4 5 6 7 8 9 10 11 | |
This interface extends Mongoose's Document type and defines the shape of our User documents, including methods like comparePassword.
Benefits of Our Type System¶
- Error Prevention: Catches type-related errors at compile time
- Self-Documentation: Types serve as documentation for data structures
- Refactoring Confidence: Makes large-scale changes safer
- IDE Support: Provides excellent autocompletion and inline documentation
- Team Collaboration: Makes it easier for team members to understand the codebase