Quick Answer
Handle missing property errors.
Understanding the Issue
TypeScript enforces type shapes, preventing access to non-existent properties.
The Problem
This code demonstrates the issue:
Typescript
Error
interface User {
name: string;
}
const user: User = { name: "John" };
console.log(user.age); // Error
The Solution
Here's the corrected code:
Typescript
Fixed
// Solution 1: Extend the interface
interface User {
name: string;
age?: number; // Optional property
}
// Solution 2: Type assertion (when certain)
console.log((user as any).age); // Not recommended
// Solution 3: Type guard
if ("age" in user) {
console.log(user.age);
}
// Solution 4: Index signature
interface User {
name: string;
[key: string]: unknown;
}
Key Takeaways
Properly define types or use type guards for dynamic property access.