typescript
type_error
ai_generated
true
TS2322: Type 'X' is not assignable to type 'Y'
ID: typescript/ts2322-type-not-assignable
88%Fix Rate
90%Confidence
310Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 5 | active | — | — | — |
Root Cause
Type mismatch in assignment. The most common TypeScript error.
genericWorkarounds
-
92% success Fix the type at the source (function return type, API response type, etc.)
function return type, API response type, etc.
Sources: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html
-
88% success Use type guards or narrowing to handle union types properly
if ('field' in obj) { /* obj is narrowed */ }Sources: https://www.typescriptlang.org/docs/handbook/2/narrowing.html
-
80% success Use type assertion (as Type) as a last resort after verifying correctness
// Only use when you know more than the compiler: const event = e as MouseEvent; // Prefer double assertion for incompatible types (rare): const value = input as unknown as TargetType; // Better: use a type guard instead: function isMouseEvent(e: Event): e is MouseEvent { return 'clientX' in e; }Sources: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions
Dead Ends
Common approaches that don't work:
-
Cast with 'as any'
80% fail
Removes all type safety, defeats the purpose of TypeScript
-
Add @ts-expect-error
75% fail
Silences the error without fixing the type issue
Error Chain
Preceded by:
Frequently confused with: