TypeScript Fundamentals
TypeScript adds static typing to JavaScript, making code more maintainable and catching errors early.
Type Definitions
// Basic types
type User = {
id: number;
name: string;
email: string;
active?: boolean;
};
// Union types
type Status = 'pending' | 'active' | 'inactive';
// Generic interfaces
interface Repository<T> {
find(id: string): Promise<T>;
save(item: T): Promise<T>;
}
Advanced Patterns
// Discriminated unions
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rectangle'; width: number; height: number };
function getArea(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'rectangle':
return shape.width * shape.height;
}
}
Best Practices
- Use strict mode
{
"compilerOptions": {
"strict": true
}
}
- Prefer interfaces for public APIs
- Use type inference when possible
- Leverage const assertions
- Implement proper error handling
Stay tuned for more TypeScript tips!