hooks-missing-generics
Detects missing generics on hooks in TypeScript/TSX codebases.
# Hooks Missing Generics Codemod
A JSSG codemod that detects missing generic type parameters on hooks in TypeScript/TSX codebases and adds TODO comments to flag type widening issues.
## What It Detects
### 1. useState with Empty Literals
Detects `useState([])` or `useState({})` calls without generic type parameters:
```tsx
// ❌ Flagged
const [items, setItems] = useState([]);
// ✅ Not flagged
const [items, setItems] = useState<Item[]>([]);
```
### 2. Custom Hooks Wrapping Other Hooks
Detects custom hooks that:
- Are named `useX` (following React hook naming convention)
- Call other hooks inside (useState, useQuery, useMutation, etc.)
- Don't declare generic type parameters
- Accept `Promise<any>` or return `any`/`unknown`
```tsx
// ❌ Flagged
export function useApiQuery(key: string, fn: () => Promise<any>) {
return useQuery(key, fn);
}
// ✅ Not flagged
export function useApiQuery<T>(key: string, fn: () => Promise<T>) {
return useQuery(key, fn);
}
```
### 3. Hooks with Any Types
Detects hooks that:
- Accept `Promise<any>` in parameters
- Return `any` type
```tsx
// ❌ Flagged
export function useData(): any {
const [data] = useState({});
return data;
}
```
## Usage
### Run the Codemod
```bash
npx codemod jssg run -l tsx ./scripts/codemod.ts ./path/to/target
```
### Test the Codemod
```bash
cd hooks-missing-generics-codemod
npm test
# or
npx codemod jssg test -l tsx ./scripts/codemod.ts
```
### Update Test Snapshots
```bash
npx codemod jssg test -l tsx ./scripts/codemod.ts -u
```
## Output Format
For each detected issue, the codemod adds a TODO comment above the problematic code:
```tsx
// TODO: Missing generic type parameter on useState([]) causes type widening to never[]. Add explicit type: useState<Item[]>([])
const [items, setItems] = useState([]);
```
## Rule ID
- `hooks.missing-generics` - All findings use this rule identifier
## Non-Goals
- Does not require framework-specific knowledge beyond common hooks
- Avoids false positives for hooks that intentionally return `unknown` with runtime validation
- Does not auto-fix issues (only adds TODO comments)
## Examples
See the `tests/` directory for comprehensive test cases covering:
- useState with empty arrays
- useState with empty objects
- Custom hooks wrapping hooks
- Hooks with Promise<any>
- Hooks returning any
- Negative cases (should not be flagged)