typescript type_error ai_generated true

error TS2564: Property 'X' has no initializer and is not definitely assigned in the constructor

ID: typescript/ts2564-no-initializer

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

Class property declared but not initialized. strictPropertyInitialization is enabled.

generic

Workarounds

  1. 95% success Initialize in the constructor or at declaration: property: Type = defaultValue
    property: Type = defaultValue

    Sources: https://www.typescriptlang.org/docs/handbook/2/classes.html#--strictpropertyinitialization

  2. 80% success Use definite assignment assertion (!) only when you're SURE it's set before use (e.g., DI)
    class Foo { @Inject() service!: Service; }  // OK: framework sets it

    Sources: https://www.typescriptlang.org/docs/handbook/2/classes.html

Dead Ends

Common approaches that don't work:

  1. Set strictPropertyInitialization to false 70% fail

    Disables a useful safety check across the entire project

  2. Add ! to suppress: property!: Type 60% fail

    Suppresses the check but may cause runtime undefined access

Error Chain

Leads to:
Preceded by:
Frequently confused with: