Tutorial hero
Lesson icon

Strict mode

Originally published June 30, 2022 Time 2 mins

This was something I briefly mentioned in my video this week. If you are not already, consider activating strict mode in your tsconfig.json file:

strict mode in tsconfig

This will make the TypeScript compiler complain about more things, but it is all stuff that will make your code better/safer if you address the issues it highlights. Most notably, you are going to notice the compiler complaining about values being potentially null. In the case of inputs that might mean you need to do something like this:

inputs

The exclamation mark is the non-null assertion operator. TypeScript complains because it is possible for this input to be null, but this is basically you saying: don’t worry about it, I’ll definitely always provide a value for this.

Or, maybe that input might actually be null sometimes. In which case, you will be forced to update the type to reflect that:

imputs that might me null

Another problem you will run into if you are using streams, is that the TypeScript compiler will think a value from a stream might be null - even if that value is provided synchronously. For example, if you have a stream that makes an HTTP request then it isn’t going to have a value right away and might be null, so the compiler would be right to complain.

However, you can also use a stream to provide a value synchronously, and in this case it would never be null. But, the compiler is going to assume all observable streams might be null. So, another little trick you can do is this:

observable streams

or this:

ovservable streams

Again, we are using that non-null assertion operator to let the compiler know that this value will definitely not be null.

Whether the TypeScript compiler complains about these things or not, they are still going to be issues in your app - so it is better to deal with them explicitly rather than waiting for something to potentially go wrong at runtime.

Learn to build modern Angular apps with my course