Property has no initializer and is not definitely assigned

Pranjay Poddar
3 min readMay 24, 2021

A quick fix for the most frequent error faced by Angular Developers

Now that TypeScript has been widely adopted, it’s time to get serious and go to the end of the idea: fully statically typed code. typescript-strictly-typed enables configurations for strictly typed TypeScript, ESLint or TSLint, and optionally Angular. After a new update in typescript 2.7 and above a new flag was added

--strictPropertyInitialization
also implied as
--strict

therefore many developers face this error while updating to the newer version of TypeScript 2.7
If you ever come across an error that looks like 👇

Property 'XYZ' has no initializer and is not definitely assigned in the constructor.

Then some of the probable reasons could be:

  • You might have updated your TypeScript version or strictness flags.
  • You might be using the old syntax in the updated TypeScript version.

But Don't Worry → Here's how to fix it in the following steps.

STEP-1 (Assigning The Value / Initializing The Property)

Syntax Used Before TypeScript 2.7
export class Feedback{
name : string;
Phone : number;
opinion : boolean;
}
Syntax Used After TypeScript 2.7
ecport class Feedback{
name : string;
Phone : number;
opinion : boolean;
constructor(){
this.name = "";
this.number = 0;
this.opinion = false;
}
}

Assigning a sample value inside a constructor is a quick and correct way of fixing this error. If the code base is larger then assigning all the values in the constructor would be a tedious task therefore there is an alternate syntax also available to make the code look clean and simple.👇

Alternate Syntax in TypeScript 2.7
ecport class Feedback{
name = "";
Phone = 0;
opinion = false;
}
// If this doesn't help follow Step-2

STEP- 2 (Adding A PostFix !)

TypeScript 2.7 includes a strict class checking where all the properties should be initialized in the constructor. A workaround is to add the ! as a postfix to the property/variable name to fool the compiler to avoid a strict check:

export class Feedback{
name !: string;
Phone !: number;
opinion !: boolean;
}

STEP-3 (Making Properties Optional)

Adding a question mark before colon converts the property into an optional property this force the compiler to ignore the strict check of property initialization.

export class Feedback{
name ?: string;
Phone ?: number;
opinion ?: boolean;
}

Step-4 (Changing Property In Compiler Option)|(Less Preferred)

Add "strictPropertyInitialization": falseproperty in 'compilerOptions' of tsconfig.json (mostly in Angular.js) or by changing “strict”: false, To get rid of the compilation error.

Do leave a clap if this blog helped you to fix this error.✨

--

--