TypeScript
The TypeScript skill provides expertise in strict typing, advanced type utilities, and modern TypeScript patterns.
When Activated
Section titled “When Activated”- Working with TypeScript files (
.ts,.tsx) - Building typed JavaScript applications
- React/Next.js development
- Node.js backend development
Core Patterns
Section titled “Core Patterns”Type Definitions
Section titled “Type Definitions”// Interfaces for objectsinterface User { id: string; email: string; name: string; createdAt: Date;}
// Types for unions and utilitiestype Status = 'pending' | 'active' | 'inactive';type UserWithStatus = User & { status: Status };
// Generic typestype ApiResponse<T> = { data: T; error?: string; status: number;};Utility Types
Section titled “Utility Types”// Partial - all properties optionaltype UserUpdate = Partial<User>;
// Pick - select propertiestype UserPreview = Pick<User, 'id' | 'name'>;
// Omit - exclude propertiestype UserWithoutId = Omit<User, 'id'>;
// Record - dictionary typetype UserMap = Record<string, User>;Async Patterns
Section titled “Async Patterns”async function fetchUser(id: string): Promise<User> { const response = await fetch(`/api/users/${id}`); if (!response.ok) { throw new Error(`Failed to fetch user: ${response.status}`); } return response.json();}
// Error handlingasync function safeOperation<T>( operation: () => Promise<T>): Promise<[T, null] | [null, Error]> { try { const result = await operation(); return [result, null]; } catch (error) { return [null, error as Error]; }}Class Patterns
Section titled “Class Patterns”class UserService { constructor(private readonly db: Database) {}
async findById(id: string): Promise<User | null> { return this.db.users.findUnique({ where: { id } }); }
async create(data: UserCreate): Promise<User> { return this.db.users.create({ data }); }}Zod Validation
Section titled “Zod Validation”import { z } from 'zod';
const UserSchema = z.object({ email: z.string().email(), name: z.string().min(1).max(100), password: z.string().min(8),});
type UserInput = z.infer<typeof UserSchema>;
function validateUser(data: unknown): UserInput { return UserSchema.parse(data);}Best Practices
Section titled “Best Practices”- Enable strict mode in tsconfig.json
- Avoid
any- useunknownand type guards - Use interfaces for object shapes, types for unions
- Prefer
constassertions for literal types - Use discriminated unions for state
Common Pitfalls
Section titled “Common Pitfalls”Using any
Section titled “Using any”// ❌ BAD: Defeats type safetyfunction process(data: any) { return data.value;}
// ✅ GOOD: Use unknown and type guardsfunction process(data: unknown) { if (typeof data === 'object' && data !== null && 'value' in data) { return (data as { value: string }).value; } throw new Error('Invalid data');}Not Handling Null/Undefined
Section titled “Not Handling Null/Undefined”// ❌ BAD: Assumes user existsfunction getUserName(id: string): string { const user = findUser(id); return user.name; // Might crash}
// ✅ GOOD: Handle null casefunction getUserName(id: string): string | null { const user = findUser(id); return user?.name ?? null;}Type Assertions Over Guards
Section titled “Type Assertions Over Guards”// ❌ BAD: Unsafe type assertionconst user = data as User;
// ✅ GOOD: Type guardfunction isUser(data: unknown): data is User { return ( typeof data === 'object' && data !== null && 'id' in data && 'email' in data );}
if (isUser(data)) { // data is safely typed as User here}Ignoring Errors
Section titled “Ignoring Errors”// ❌ BAD: Unhandled rejectionasync function loadData() { const data = await fetchData(); return data;}
// ✅ GOOD: Handle errorsasync function loadData() { try { const data = await fetchData(); return data; } catch (error) { console.error('Failed to load data:', error); throw error; }}Integration with Frameworks
Section titled “Integration with Frameworks”With React
Section titled “With React”See React skill for component patterns.
With Next.js
Section titled “With Next.js”See Next.js skill for full-stack patterns.
Related Skills
Section titled “Related Skills”- JavaScript - Parent language
- React - UI components
- Next.js - Full-stack framework
- vitest - Testing framework