Quick Answer
Type mismatch in assignments or returns
Understanding the Issue
TypeScript uses structural typing but still enforces type compatibility. This error occurs when trying to assign or return a value of the wrong type.
The Problem
This code demonstrates the issue:
Typescript
Error
// Problem: Type mismatch
interface Animal { name: string; }
interface Dog extends Animal { breed: string; }
let animal: Animal = { name: "Rex" };
let dog: Dog = animal; // Error
The Solution
Here's the corrected code:
Typescript
Fixed
// Solution 1: Correct type assignment
let dog: Dog = { name: "Rex", breed: "Labrador" };
// Solution 2: Type assertion (when certain)
let dog = animal as Dog; // Unsafe
// Solution 3: Use intersection type
let animalDog: Animal & { breed?: string } = animal;
Key Takeaways
Ensure types are compatible in assignments or use proper type assertions.