Angular provides a set of compiler options to enforce stricter type checking and improve the overall application quality. In this answer, we will discuss two of these options: ‘strictTemplates‘ and ‘strictInjectionParameters‘.
1. ‘strictTemplates‘
Introduced in Angular version 9, ‘strictTemplates‘ enables a series of strict type-checking options for Angular templates. By default, this option is set to ‘false‘. If you enable this option in the ‘tsconfig.json‘ file, it will ensure that:
- Expressions used in templates have the correct type.
- Proper type checking is performed for input bindings.
- Type-checking is enforced for local refs and views.
- Correct return types are ensured for pipes.
To enable ‘strictTemplates‘, set the option to ‘true‘ in your ‘tsconfig.json‘ file:
{
"angularCompilerOptions": {
"strictTemplates": true
}
}
This option is a shorthand for enabling multiple strict type checking options, including:
- ‘fullTemplateTypeCheck‘: Perform type checking in template expressions.
- ‘strictNullChecks‘: Ensure strict null checking is performed.
- ‘strictInputTypes‘: Ensure strict type checking for input bindings.
- ‘strictAttributeTypes‘: Ensure strict type checking for ElementRef, ElementRef, HTMLElement, and NgModule attributes.
By using this option, you can catch type-related problems and possible bugs in the early stages, making it easier to maintain the application in the long run.
2. ‘strictInjectionParameters‘
This option enforces strict checking of parameters injected by the Angular DI (Dependency Injection) system. By default, this option is set to ‘false‘. When ‘strictInjectionParameters‘ is enabled, the Angular compiler will report an error if it cannot determine the correct type for an injected parameter. This helps to catch potential issues that can arise from improperly typed or missing tokens in the DI system.
To enable ‘strictInjectionParameters‘, set the option to ‘true‘ in your ‘tsconfig.json‘ file:
{
"angularCompilerOptions": {
"strictInjectionParameters": true
}
}
By enabling ‘strictTemplates‘ and ‘strictInjectionParameters‘, you can improve the overall quality of your Angular application. These options help ensure that type-related issues are caught as early as possible, making it much easier to maintain and debug the application over time.