The upcoming version 2.7 release of TypeScript has a new compiler option available named "strictPropertyInitialization" This when set to true causes the compiler to ensure all properties in class instances are initialized. If they are not, a compiler error will be generated upon building for each uninitialized property.As an aside, to get the most current version of TypeScript installed that hasn't yet been officially released you can run the following npm command:

npm install -g typescript@next

This installs the most recent nightly build which will allow me to have access to the new compiler option:+ typescript@2.7.0-dev.20180113 If you are beginning a new project, wait to initialize your TypeScript project until after the newest version is installed, so you can easily see all the new compiler options. You can also add them manually to your existing tsconfig.json file. Upon initializing a fresh tsconfig file (tsc --init), you will see the new strictPropertyInitializationcheck:

With "strictPropertyInitialization":true set, the following compiler errors will be emitted upon building:error TS2564: Property 'firstName' has no initializer and is not definitely assigned in the constructor.error TS2564: Property 'lastName' has no initializer and is not definitely assigned in the constructor.error TS2564: Property 'address1' has no initializer and is not definitely assigned in the constructor.error TS2564: Property 'address2' has no initializer and is not definitely assigned in the constructor.This is exactly what we would expect. One way to satisfy the check we can do is mark the parameter as optional using the ? as we might with address2. This will remove the error related with this field, as undefined is acceptable:

The build now only generates 3 errors:error TS2564: Property 'firstName' has no initializer and is not definitely assigned in the constructor.error TS2564: Property 'lastName' has no initializer and is not definitely assigned in the constructor.error TS2564: Property 'address1' has no initializer and is not definitely assigned in the constructor.To satisfy the strict property initialization for the rest of the class, we can initialize the remaining properties and we will get a successful build:

There is also a way if needed to individually suppress the property initialization checks on an individual basis. This can be done by including a definite assignment assertion using a ! mark immediately after the property name. This will allow the following to build successfully:

Related Postings:

0
comments:

Post a Comment

About Me

I am a Magenic Practice Lead that is an advocate of web client and Microsoft .NET technologies both professionally and personally. I enjoy the challenge and creativity behind software engineering, and hope during this process to extract some of my thoughts and ideas in order to give back to others in the community through public speaking and here on this blog.