typescript type_error ai_generated true

error TS2339: Property 'x' does not exist on type 'Y'

ID: typescript/ts2339-property-not-exist

Also available as: JSON · Markdown
90%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

Accessing property not in type definition. Common with API responses and DOM.

generic

Workarounds

  1. 92% success Extend the type definition or use type assertion with proper type
    interface Extended extends Base { newProp: string }

    Sources: https://www.typescriptlang.org/docs/handbook/2/objects.html#extending-types

  2. 88% success Use 'in' operator for type narrowing
    if ('prop' in obj) { obj.prop }

    Sources: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-in-operator-narrowing

  3. 85% success Add an index signature or use Record type if the property is dynamic
    // Index signature on interface:
    interface DynamicObj {
      name: string;
      [key: string]: unknown;
    }
    
    // Or use Record for fully dynamic objects:
    const config: Record<string, string> = {};
    config.anyProp = 'value';  // no error

    Sources: https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures

Dead Ends

Common approaches that don't work:

  1. Cast to any 80% fail

    Removes all type safety

  2. Add // @ts-expect-error 75% fail

    Silences compiler without fixing the type

Error Chain

Leads to:
Preceded by:
Frequently confused with: