Quick Answer
Handle type mismatch issues.
Understanding the Issue
TypeScript prevents assignments between incompatible types to catch bugs early.
The Problem
This code demonstrates the issue:
Typescript
Error
const num: number = "hello"; // Error
The Solution
Here's the corrected code:
Typescript
Fixed
// Solution 1: Correct the type
const str: string = "hello";
// Solution 2: Type assertion
const num = "123" as unknown as number; // Last resort
// Solution 3: Runtime validation
function isNumber(x: unknown): x is number {
return typeof x === "number";
}
// Solution 4: Union type
let value: string | number = "hello";
value = 42; // Valid
Key Takeaways
Maintain type consistency or use proper type conversions.