How to Fix TypeScript Errors in AI-Generated Code: A Practical Guide
Fix the most common TypeScript errors in AI-generated code — type mismatches, missing imports, 'any' leaks, and generic hallucinated types. With real before/after examples.
Why AI Gets TypeScript Wrong
AI models are great at producing code that looks like TypeScript, but they regularly produce code with type errors. Why?
1. Models memorize patterns, not type signatures — They've seen lots of JavaScript code and add types as an afterthought
2. They hallucinate TypeScript APIs — Methods that don't exist, wrong parameter types
3. They use loose types — Everything becomes any when the model isn't confident
4. Context drift — In long sessions, the AI "forgets" your type definitions
The good news: TypeScript errors from AI code are usually easy to fix once you know the patterns. This guide covers the most common ones and how to resolve them.
External Links: - TypeScript Handbook — official reference - TypeScript Playground — test types before using
---
Error 1: Implicit any Everywhere
// AI-generated:
function processItems(items) {
return items.map(item => item.name)
}
// Error: Parameter 'items' implicitly has 'any' type
// Error: Parameter 'item' implicitly has 'any' type
Why It Happens
AI models default to plain JavaScript unless explicitly told to add types. In strict TypeScript projects, this causes implicit any errors.
Fix: Prompt with Types
Include types in your prompt:
Create a function processItems that accepts Item[] and returns string[]
Better yet, define the type first and let Claude reference it, or type the function yourself:
// Corrected:
type Item = { id: number; name: string }function processItems(items: Item[]): string[] {
return items.map(item => item.name)
}
Fix: Configure Strict Mode
Ensure your tsconfig.json catches these:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUnusedLocals": true,
"noUnusedParameters": true
}
}
---
Error 2: Hallucinated Type Imports
// AI-generated:
import { UserRole, PermissionFlags } from '@prisma/client'
// Error: Module '@prisma/client' does not export 'PermissionFlags'
Why It Happens
The model guesses what a library exports based on similar patterns it's seen. Unless the exact type is in its training data, it will invent something plausible-looking.
Fix: Check the Actual Exports
# Check what @prisma/client actually exports
npx tsc --declaration --emitDeclarationOnly
# Look at the generated .d.ts files# Or use a type explorer
npx ts-node -e "import '@prisma/client'; console.log('Module loaded')"
Fix: Generate Types First
For Prisma:
npx prisma generate
This creates the actual type definitions. Then re-prompt the AI with the generated types available in node_modules/.prisma/client/.
External Links: - Prisma Client Type Generation - DefinitelyTyped (@types) — community type definitions
---
Error 3: Wrong React/Next.js Types
// AI-generated (for Next.js App Router):
export default function Page(props) {
// Error: Binding element 'params' implicitly has 'any' type
}// AI writes this:
export default function HomePage({ params }: { params: { id: string } }) {
// Error: Type '{ params: { id: string } }' is not assignable to type 'PageProps'
}
Why It Happens
Next.js App Router has specific type conventions that the AI gets wrong. The page component should use Next.js's PageProps type.
Fix: Use the Correct Next.js Types
// Next.js App Router — correct types:
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'// For pages that use params:
type PageProps = {
params: Promise<{ id: string }>
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}
export default async function Page({ params }: PageProps) {
const { id } = await params
// ...
}
> 💡 Pro tip: Ask the AI to use Next.js's built-in types explicitly: >
> Create a Next.js App Router page with proper Next.js type imports
> External Links: - Next.js TypeScript Documentation - Next.js Page Props Types
---
Error 4: Missing Generic Types
// AI-generated:
const result = useState([])
// Result is 'any[]'const response = await fetch('/api/users')
const data = response.json()
// Data is 'Promise'
Why It Happens
The model doesn't specify generic types, defaulting to any. This type error propagates through your entire codebase.
Fix: Add Generic Parameters
// Corrected:
const [items, setItems] = useState- ([])
// For fetch:
interface UserResponse {
users: User[]
total: number
}
const response = await fetch('/api/users')
const data: UserResponse = await response.json()
When prompting, specify the types:
Create a React component that uses useState for a user list
---
Error 5: null and undefined Handling
// AI-generated:
const user = users.find(u => u.id === userId)
console.log(user.name) // Error: Object is possibly 'undefined'
Why It Happens
Array.find() returns T | undefined, but the AI treats it as if it definitely returns a value. This is one of the most common TypeScript errors in AI-generated code.
Fix: Add Proper Null Checks
// Option 1: Guard clause
const user = users.find(u => u.id === userId)
if (!user) {
throw new Error(User ${userId} not found)
}
console.log(user.name) // ✓ TypeScript is happy now// Option 2: Default value
const userName = users.find(u => u.id === userId)?.name ?? 'Unknown'
// Option 3: Non-null assertion (use sparingly)
const user = users.find(u => u.id === userId)!
// Only use when you're 100% sure it exists
Related Articles: - How to Debug AI-Generated Code — broader debugging strategies
---
Error 6: Overly Broad Return Types
// AI-generated:
function fetchData(): any {
// returns User | Product | Order
}
Why It Happens
The AI uses any as a crutch when it's unsure about the return type. This defeats the purpose of TypeScript.
Fix: Use Union Types or Overloads
// Better: Union type
function fetchData(type: 'user'): Promise
function fetchData(type: 'product'): Promise
function fetchData(type: 'order'): Promise
function fetchData(type: string): Promise {
// implementation...
}
---
Error 7: Wrong Async/Await Types
// AI-generated:
const data = await fetchData()
processData(data)// But fetchData() actually returns:
function fetchData(): Promise
Why It Happens
The AI doesn't verify the actual return type of your functions. It assumes the most common case.
Fix: Type the Response
// Use type narrowing:
const result = await fetchData()
if (result instanceof Error) {
console.error('Failed to fetch:', result.message)
return
}// Or use a Result type pattern:
type Result = { success: true; data: T } | { success: false; error: string }
const result = await fetchData()
if (!result.success) {
console.error(result.error)
return
}
---
Error 8: Missing Type Annotations on Event Handlers
// AI-generated:
// Error: Parameter 'e' implicitly has 'any' type
Fix: Use React SyntheticEvent
// Method 1: Inline type
For other common event types:
// Form submission
const handleSubmit = (e: React.FormEvent): void => {}// Input change
const handleChange = (e: React.ChangeEvent): void => {}
// Keyboard events
const handleKeyDown = (e: React.KeyboardEvent): void => {}
External Links: - React TypeScript Cheatsheet — comprehensive type reference - React Event Types Documentation
---
Error 9: Generic Type Mismatch
// AI-generated:
interface ApiResponse {
data: T
status: number
}// But then:
const response: ApiResponse = await getUsers()
// Error: Generic type 'ApiResponse' requires 1 type argument(s)
Fix: Always Provide Generic Parameters
const response: ApiResponse = await getUsers()
// Or let TypeScript infer it:
const response = await getUsers() // if getUsers() is typed properly
---
Error 10: Circular Type Dependencies
// AI can generate this:
type TreeNode = {
value: string
children: TreeNode[] // Self-referential — fine
parent: TreeNode // Also self-referential — might cause issues
}
These aren't always wrong, but the AI can overdo circular references.
Fix: Simplify the Type
type TreeNode = {
value: string
children: TreeNode[]
}// Store parent separately if needed
type TreeNodeWithParent = TreeNode & {
parent?: TreeNode['value'] // Reference by ID, not reference
}
---
Quick Fix: The "Make TypeScript Happy" Prompt
When Claude Code generates TypeScript that doesn't compile, try this prompt:
The following TypeScript code has type errors. Fix all type errors while keeping the logic the same.
[ERROR OUTPUT]
[CODE]
This forces the AI to focus specifically on types rather than rewriting the logic.
---
Prevention: Add TypeScript Rules to CLAUDE.md
Prevent type errors before they happen:
# .claude/CLAUDE.md
TypeScript Rules
- Every function must have explicit parameter and return types
- Never use any — prefer unknown if type is truly unknown
- Use interface for object shapes, type for unions/intersections
- Always handle null/undefined with optional chaining and nullish coalescing
- Use const assertions for literal types: as const
- Prefer type imports: import type { X } over import { X }
Related Articles: - Effective Claude Code Prompts — prompt strategies for better code - How to Debug AI-Generated Code — systematic debugging approach - Agent Skills for Claude Code — extend Claude Code with custom lint rules
Related Articles
How to Debug AI-Generated Code: A Practical Guide for Developers
Master the art of debugging code written by AI coding agents. Learn systematic approaches to verify, test, and fix AI-generated code before it hits production.
Crush vs Claude Code: Open Source vs Pro AI Coding Agent (2026)
Comprehensive comparison of Crush (successor to OpenCode) vs Claude Code — the two most talked-about terminal AI coding agents. Covers features, setup, cost, multi-model support, and which one to choose for your workflow.
The Truth About AI Coding in 2026: What Works, What Doesn't, and How to Get Real Results
An honest look at AI-assisted coding in 2026 — where AI coding agents excel, where they fail, the '70% problem,' and a practical framework for getting real productivity gains without the hype.