Quick Answer
Attempting to access undeclared properties
Understanding the Issue
TypeScript performs static type checking and will prevent access to properties that aren't declared in the type definition. This ensures type safety and catches typos.
The Problem
This code demonstrates the issue:
Typescript
Error
// Problem: Undeclared property
interface Person {
name: string;
}
const p: Person = { name: "Alice" };
console.log(p.age); // Error
The Solution
Here's the corrected code:
Typescript
Fixed
// Solution 1: Add property to interface
interface Person {
name: string;
age?: number; // Optional
}
// Solution 2: Type assertion (when certain)
console.log((p as any).age); // Not recommended
// Solution 3: Use type with index signature
interface FlexiblePerson {
name: string;
[key: string]: any;
}
Key Takeaways
Ensure all accessed properties are properly declared in the type definition.