StrictPropertyInitialization in TypeScript

strictPropertyInitialization (Strict Property Initialization) in Typescript is a compiler flag, which when set to true, forces us to assign an initial value to all class properties. If we fail to do so then the compiler will raise the “Property has no initializer and is not definitely assigned in the constructor.” error. This flag was introduced in Typescript 2.7

Setting strictPropertyInitialization

There are two ways in which you can enable strict property initialization in TypeScript.

One is to enable the strict option in tsconfig.ts

or set the strictPropertyInitialization to true or false. This will override the "strict" option.

Note that the --strictNullChecks flag must be set (either directly or indirectly via --strict) in order for --strictPropertyInitialization to have any effect.

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

When we declare a property without assigning an initial value, the compiler raises the “Property has no initializer and is not definitely assigned in the constructor” error.

There are several ways in which you can solve the above problem

Provide an initial value

There are two ways in which you can provide an initial value to the property. One is setting it explicitly when declaring the property

Another method is to use the constructor function to assign a initial value.

Make the property optional

You can also make the Property optional.

Use a type that has undefined as one of its value

You can assign the type undefined to the property or any type that allows undefined. For example union type of string & undefined.

Use the definite assignment assertion typescript

The definite assignment assertion is a feature that typescript introduced in version 2.7. We can use it to tell the typescript compiler that we will take care of giving the property its initial value. We do that by placing ! after instance property ( also any variable declaration). The compiler will not raise an error even if detects that the class property lacks an initial value.

Set strictPropertyInitialization to false.

You can also set strictPropertyInitialization to false in the tsconfg.ts. If possible avoid using this option.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top