TypeScript Code Review Skill
Perform thorough, professional code reviews for TypeScript code with focus on type safety, best practices, performance, security, and maintainability.
Review Process
When reviewing TypeScript code, follow this structured approach:
1. Initial Assessment
- Understand the code's purpose and context
- Identify the scope (single file, module, feature, or entire codebase)
- Note the TypeScript version and configuration (check
tsconfig.json)
- Review any relevant documentation or comments
2. Core Review Categories
Type Safety
- Strict mode compliance: Verify
strict: true in tsconfig.json and adherence
- Type annotations: Check for proper type annotations, avoid implicit
any
- Type narrowing: Ensure proper use of type guards and narrowing
- Generic types: Review generic usage for flexibility without sacrificing safety
- Union and intersection types: Verify correct usage and handling
- Type assertions: Flag unnecessary or dangerous type assertions (the
as keyword and non-null assertion operator)
- Null/undefined handling: Check for proper optional chaining (
?.) and nullish coalescing (??)
- Return types: Ensure all functions have explicit return types
- Discriminated unions: Verify proper exhaustiveness checking
Code Quality & Best Practices
- Naming conventions: Check for clear, descriptive names (camelCase for variables/functions, PascalCase for types/classes)
- Function length: Flag functions longer than ~50 lines or with high complexity
- Single responsibility: Ensure functions and classes have one clear purpose
- DRY principle: Identify duplicate code that should be extracted
- Magic numbers/strings: Flag hardcoded values that should be constants
- Error handling: Review try-catch usage, error types, and error messages
- Async/await: Check for proper async handling, avoid mixing callbacks/promises
- Immutability: Prefer
const over let, check for array/object mutations
- Enums vs unions: Recommend const enums or union types over regular enums when appropriate
Modern TypeScript Features
- Optional chaining: Suggest using
?. for nested property access
- Nullish coalescing: Recommend
?? over || for default values
- Template literal types: Check for opportunities to use template literals
- Utility types: Suggest
Partial, Pick, Omit, Record, etc. where appropriate
- Const assertions: Recommend
as const for literal types
- Type predicates: Use for custom type guards
satisfies operator: Use instead of type assertions when validating types
Performance
- Unnecessary re-renders: In React/frameworks, check for memo usage, dependency arrays
- Large bundle imports: Flag entire library imports when tree-shaking is possible
- Inefficient algorithms: Identify O(n²) or worse when better options exist
- Memory leaks: Check for cleanup in event listeners, subscriptions, timers
- Lazy loading: Suggest dynamic imports for large modules
- Type calculation cost: Flag extremely complex type calculations that slow compilation
Security
- Input validation: Ensure user input is validated and sanitized
- XSS vulnerabilities: Check for unsafe HTML rendering or
eval usage
- Sensitive data: Flag hardcoded secrets, tokens, or passwords
- Dependency vulnerabilities: Recommend running
npm audit or checking dependencies
- Type safety as security: Ensure types prevent security issues (e.g., SQL injection through tagged templates)
Testing & Maintainability
- Test coverage: Note missing tests for critical paths
- Type-only imports: Use
import type for type-only imports
- Circular dependencies: Flag circular imports
- Barrel exports: Check for performance issues with index files
- Documentation: Verify JSDoc comments for public APIs
- Deprecation notices: Ensure deprecated code is properly marked
3. Output Structure
Organize the review with clear sections:
## Summary
[High-level overview: overall code quality, main concerns, highlights]
## Critical Issues 🔴
[Issues that must be fixed: type errors, security vulnerabilities, breaking bugs]
## Important Improvements 🟡
[Significant issues affecting maintainability, performance, or best practices]
## Suggestions 🔵
[Nice-to-have improvements, style preferences, optimizations]
## Positive Observations ✅
[What the code does well, good patterns to reinforce]
## Detailed Findings
### [Category 1: e.g., Type Safety]
**File**: `path/to/file.ts:line_number`
- **Issue**: [Description]
- **Current code**:
```typescript
[code snippet]
- Recommended:
[improved code]
- Reasoning: [Why this matters]
[Repeat for each finding]
### 4. Code Review Guidelines
**Tone and Style**:
- Be constructive and specific, not vague or critical
- Explain the "why" behind recommendations
- Provide code examples for suggested changes
- Acknowledge good practices when present
- Use severity indicators (🔴 critical, 🟡 important, 🔵 suggestion)
**Prioritization**:
1. Critical: Security issues, type errors, runtime bugs
2. Important: Performance problems, maintainability issues, anti-patterns
3. Suggestions: Style improvements, modern syntax, optimizations
**Context Awareness**:
- Consider the project's maturity (prototype vs production)
- Respect existing patterns if consistent across codebase
- Note tradeoffs (e.g., performance vs readability)
- Reference the project's TypeScript configuration
### 5. Reference Files
For detailed guidance on specific topics, consult the reference files:
- `references/type-safety-checklist.md` - Comprehensive type safety review points
- `references/common-antipatterns.md` - TypeScript anti-patterns to avoid
- `references/security-checklist.md` - Security considerations for TypeScript
- `references/performance-tips.md` - Performance optimization strategies
Search references using Grep when encountering specific issues. For example:
- Type guard issues: grep "type guard" in `references/type-safety-checklist.md`
- Performance concerns: grep "performance" in `references/performance-tips.md`
### 6. TypeScript Configuration Review
When reviewing `tsconfig.json`, check for:
**Recommended strict settings**:
```json
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true
}
}
7. Framework-Specific Considerations
React + TypeScript:
- Component prop types with interfaces
- Proper typing for hooks (
useState, useEffect, useCallback, etc.)
- Event handler types (e.g.,
React.MouseEvent<HTMLButtonElement>)
- Ref types (
useRef<HTMLDivElement>(null))
- Children typing (
React.ReactNode vs React.ReactElement)
Node.js + TypeScript:
- Proper types for Express/Fastify handlers
- Async error handling in middleware
- Environment variable typing
- Database query result typing
Testing:
- Type-safe mocks and stubs
- Proper typing for test utilities (Jest, Vitest, etc.)
- Type assertions in tests
8. Automated Checks to Recommend
Suggest running these tools if not already in use:
- TypeScript compiler:
tsc --noEmit for type checking
- ESLint: With
@typescript-eslint/parser and recommended rules
- Prettier: For consistent formatting
- ts-prune: Find unused exports
- depcheck: Find unused dependencies
- madge: Detect circular dependencies
9. Review Workflow
- Scan for critical issues first: Type errors, security issues, obvious bugs
- Review architecture: File structure, module boundaries, separation of concerns
- Deep dive into logic: Algorithm correctness, edge cases, error handling
- Check types thoroughly: Accuracy, safety, appropriate use of TypeScript features
- Performance review: Identify bottlenecks, unnecessary work, optimization opportunities
- Style and consistency: Naming, formatting, pattern adherence
- Testing and docs: Coverage, clarity, maintainability
10. Example Interaction
User: "Review this TypeScript file for issues"
Response Flow:
- Read the file(s) provided
- Check for any
tsconfig.json in the project
- Perform systematic review across all categories
- Structure findings with severity levels
- Provide specific, actionable recommendations with code examples
- Highlight positive practices
- Suggest next steps (run specific tools, add tests, refactor specific areas)
Best Practices
- Be thorough but practical: Focus on issues that matter
- Provide context: Explain why something is an issue and what problems it could cause
- Show, don't just tell: Include code examples for recommendations
- Consider the audience: Adjust detail level based on the team's TypeScript experience
- Stay current: Reference modern TypeScript features (4.9+, 5.0+)
- Balance: Don't let perfect be the enemy of good—acknowledge tradeoffs
When to Use This Skill
Activate this skill when the user:
- Explicitly asks for a code review of TypeScript code
- Requests feedback on TypeScript implementation
- Asks to check code for issues, bugs, or improvements
- Wants to ensure TypeScript best practices are followed
- Needs help improving code quality or type safety
- Requests a security or performance audit of TypeScript code
1---2name: typescript-code-review3description: Perform comprehensive code reviews for TypeScript projects, analyzing type safety, best practices, performance, security, and code quality with actionable feedback4---56# TypeScript Code Review Skill78Perform thorough, professional code reviews for TypeScript code with focus on type safety, best practices, performance, security, and maintainability.910## Review Process1112When reviewing TypeScript code, follow this structured approach:1314### 1. Initial Assessment15- Understand the code's purpose and context16- Identify the scope (single file, module, feature, or entire codebase)17- Note the TypeScript version and configuration (check `tsconfig.json`)18- Review any relevant documentation or comments1920### 2. Core Review Categories2122#### Type Safety23- **Strict mode compliance**: Verify `strict: true` in tsconfig.json and adherence24- **Type annotations**: Check for proper type annotations, avoid implicit `any`25- **Type narrowing**: Ensure proper use of type guards and narrowing26- **Generic types**: Review generic usage for flexibility without sacrificing safety27- **Union and intersection types**: Verify correct usage and handling28- **Type assertions**: Flag unnecessary or dangerous type assertions (the `as` keyword and non-null assertion operator)29- **Null/undefined handling**: Check for proper optional chaining (`?.`) and nullish coalescing (`??`)30- **Return types**: Ensure all functions have explicit return types31- **Discriminated unions**: Verify proper exhaustiveness checking3233#### Code Quality & Best Practices34- **Naming conventions**: Check for clear, descriptive names (camelCase for variables/functions, PascalCase for types/classes)35- **Function length**: Flag functions longer than ~50 lines or with high complexity36- **Single responsibility**: Ensure functions and classes have one clear purpose37- **DRY principle**: Identify duplicate code that should be extracted38- **Magic numbers/strings**: Flag hardcoded values that should be constants39- **Error handling**: Review try-catch usage, error types, and error messages40- **Async/await**: Check for proper async handling, avoid mixing callbacks/promises41- **Immutability**: Prefer `const` over `let`, check for array/object mutations42- **Enums vs unions**: Recommend const enums or union types over regular enums when appropriate4344#### Modern TypeScript Features45- **Optional chaining**: Suggest using `?.` for nested property access46- **Nullish coalescing**: Recommend `??` over `||` for default values47- **Template literal types**: Check for opportunities to use template literals48- **Utility types**: Suggest `Partial`, `Pick`, `Omit`, `Record`, etc. where appropriate49- **Const assertions**: Recommend `as const` for literal types50- **Type predicates**: Use for custom type guards51- **`satisfies` operator**: Use instead of type assertions when validating types5253#### Performance54- **Unnecessary re-renders**: In React/frameworks, check for memo usage, dependency arrays55- **Large bundle imports**: Flag entire library imports when tree-shaking is possible56- **Inefficient algorithms**: Identify O(n²) or worse when better options exist57- **Memory leaks**: Check for cleanup in event listeners, subscriptions, timers58- **Lazy loading**: Suggest dynamic imports for large modules59- **Type calculation cost**: Flag extremely complex type calculations that slow compilation6061#### Security62- **Input validation**: Ensure user input is validated and sanitized63- **XSS vulnerabilities**: Check for unsafe HTML rendering or `eval` usage64- **Sensitive data**: Flag hardcoded secrets, tokens, or passwords65- **Dependency vulnerabilities**: Recommend running `npm audit` or checking dependencies66- **Type safety as security**: Ensure types prevent security issues (e.g., SQL injection through tagged templates)6768#### Testing & Maintainability69- **Test coverage**: Note missing tests for critical paths70- **Type-only imports**: Use `import type` for type-only imports71- **Circular dependencies**: Flag circular imports72- **Barrel exports**: Check for performance issues with index files73- **Documentation**: Verify JSDoc comments for public APIs74- **Deprecation notices**: Ensure deprecated code is properly marked7576### 3. Output Structure7778Organize the review with clear sections:7980```markdown81## Summary82[High-level overview: overall code quality, main concerns, highlights]8384## Critical Issues 🔴85[Issues that must be fixed: type errors, security vulnerabilities, breaking bugs]8687## Important Improvements 🟡88[Significant issues affecting maintainability, performance, or best practices]8990## Suggestions 🔵91[Nice-to-have improvements, style preferences, optimizations]9293## Positive Observations ✅94[What the code does well, good patterns to reinforce]9596## Detailed Findings9798### [Category 1: e.g., Type Safety]99**File**: `path/to/file.ts:line_number`100- **Issue**: [Description]101- **Current code**:102 ```typescript103 [code snippet]104 ```105- **Recommended**:106 ```typescript107 [improved code]108 ```109- **Reasoning**: [Why this matters]110111[Repeat for each finding]112```113114### 4. Code Review Guidelines115116**Tone and Style**:117- Be constructive and specific, not vague or critical118- Explain the "why" behind recommendations119- Provide code examples for suggested changes120- Acknowledge good practices when present121- Use severity indicators (🔴 critical, 🟡 important, 🔵 suggestion)122123**Prioritization**:1241. Critical: Security issues, type errors, runtime bugs1252. Important: Performance problems, maintainability issues, anti-patterns1263. Suggestions: Style improvements, modern syntax, optimizations127128**Context Awareness**:129- Consider the project's maturity (prototype vs production)130- Respect existing patterns if consistent across codebase131- Note tradeoffs (e.g., performance vs readability)132- Reference the project's TypeScript configuration133134### 5. Reference Files135136For detailed guidance on specific topics, consult the reference files:137138- `references/type-safety-checklist.md` - Comprehensive type safety review points139- `references/common-antipatterns.md` - TypeScript anti-patterns to avoid140- `references/security-checklist.md` - Security considerations for TypeScript141- `references/performance-tips.md` - Performance optimization strategies142143Search references using Grep when encountering specific issues. For example:144- Type guard issues: grep "type guard" in `references/type-safety-checklist.md`145- Performance concerns: grep "performance" in `references/performance-tips.md`146147### 6. TypeScript Configuration Review148149When reviewing `tsconfig.json`, check for:150151**Recommended strict settings**:152```json153{154 "compilerOptions": {155 "strict": true,156 "noUncheckedIndexedAccess": true,157 "noImplicitOverride": true,158 "noPropertyAccessFromIndexSignature": true,159 "exactOptionalPropertyTypes": true,160 "noFallthroughCasesInSwitch": true,161 "noImplicitReturns": true,162 "noUnusedLocals": true,163 "noUnusedParameters": true164 }165}166```167168### 7. Framework-Specific Considerations169170**React + TypeScript**:171- Component prop types with interfaces172- Proper typing for hooks (`useState`, `useEffect`, `useCallback`, etc.)173- Event handler types (e.g., `React.MouseEvent<HTMLButtonElement>`)174- Ref types (`useRef<HTMLDivElement>(null)`)175- Children typing (`React.ReactNode` vs `React.ReactElement`)176177**Node.js + TypeScript**:178- Proper types for Express/Fastify handlers179- Async error handling in middleware180- Environment variable typing181- Database query result typing182183**Testing**:184- Type-safe mocks and stubs185- Proper typing for test utilities (Jest, Vitest, etc.)186- Type assertions in tests187188### 8. Automated Checks to Recommend189190Suggest running these tools if not already in use:191- **TypeScript compiler**: `tsc --noEmit` for type checking192- **ESLint**: With `@typescript-eslint/parser` and recommended rules193- **Prettier**: For consistent formatting194- **ts-prune**: Find unused exports195- **depcheck**: Find unused dependencies196- **madge**: Detect circular dependencies197198### 9. Review Workflow1992001. **Scan for critical issues first**: Type errors, security issues, obvious bugs2012. **Review architecture**: File structure, module boundaries, separation of concerns2023. **Deep dive into logic**: Algorithm correctness, edge cases, error handling2034. **Check types thoroughly**: Accuracy, safety, appropriate use of TypeScript features2045. **Performance review**: Identify bottlenecks, unnecessary work, optimization opportunities2056. **Style and consistency**: Naming, formatting, pattern adherence2067. **Testing and docs**: Coverage, clarity, maintainability207208### 10. Example Interaction209210**User**: "Review this TypeScript file for issues"211212**Response Flow**:2131. Read the file(s) provided2142. Check for any `tsconfig.json` in the project2153. Perform systematic review across all categories2164. Structure findings with severity levels2175. Provide specific, actionable recommendations with code examples2186. Highlight positive practices2197. Suggest next steps (run specific tools, add tests, refactor specific areas)220221## Best Practices222223- **Be thorough but practical**: Focus on issues that matter224- **Provide context**: Explain why something is an issue and what problems it could cause225- **Show, don't just tell**: Include code examples for recommendations226- **Consider the audience**: Adjust detail level based on the team's TypeScript experience227- **Stay current**: Reference modern TypeScript features (4.9+, 5.0+)228- **Balance**: Don't let perfect be the enemy of good—acknowledge tradeoffs229230## When to Use This Skill231232Activate this skill when the user:233- Explicitly asks for a code review of TypeScript code234- Requests feedback on TypeScript implementation235- Asks to check code for issues, bugs, or improvements236- Wants to ensure TypeScript best practices are followed237- Needs help improving code quality or type safety238- Requests a security or performance audit of TypeScript code