TS2339: Property 'X' does not exist on type 'Y'
What’s happening?
Section titled “What’s happening?”This error occurs when you try to access a property that doesn’t exist on the type according to TypeScript.
Reproduction
Section titled “Reproduction”interface User { name: string; email: string;}
const user: User = { name: "Alice", email: "alice@example.com" };console.log(user.age);// ❌ Property 'age' does not exist on type 'User'Solutions
Section titled “Solutions”Option 1: Add the property to the interface
Section titled “Option 1: Add the property to the interface”interface User { name: string; email: string; age?: number; // ✅ Made optional}
const user: User = { name: "Alice", email: "alice@example.com" };console.log(user.age); // ✅ Returns undefinedOption 2: Use a type assertion (if you know the runtime shape)
Section titled “Option 2: Use a type assertion (if you know the runtime shape)”interface ExtendedUser extends User { age: number;}
const user = { name: "Alice", email: "alice@example.com", age: 30 };console.log((user as ExtendedUser).age); // ✅Option 3: Use index signatures for dynamic properties
Section titled “Option 3: Use index signatures for dynamic properties”interface User { name: string; email: string; [key: string]: any; // ✅ Allows any additional properties}Common scenarios
Section titled “Common scenarios”API responses with extra fields
Section titled “API responses with extra fields”const response = await fetch('/api/user');const data = await response.json();console.log(data.username);// ❌ Property 'username' does not exist on type 'any'
// ✅ Fix: Define the expected shapeinterface ApiResponse { username: string; email: string;}
const data: ApiResponse = await response.json();console.log(data.username); // ✅Key takeaways
Section titled “Key takeaways”- Define all properties in your interfaces
- Use optional properties (
?) for fields that might not exist - Prefer type definitions over
any