We are building an application in Angular 2 and TypeScript. We try to statically check types where it is possible. Is there any way to check types in templates? Consider the following fragment:
<foo [data]="dataObj"></foo>
Assume that data
in Foo
component has some type TData
. However, by default, nothing prevents me from passing dataObj
that does not conform to TData
. Is there a typescript extension for Angular templates that would verify the types in such a case?
Overview of template type checkinglink. Just as TypeScript catches type errors in your code, Angular checks the expressions and bindings within the templates of your application and can report any type errors it finds.
To be more precise, Angular creates Type Check Blocks (TCBs) based on the component template. Basically, a Type Check Block is a block of TypeScript code which can be inlined into source files, and when type checked by the TypeScript compiler will give us information about any typing errors in template expressions.
strictTemplates is a parameter for the angular compiler. In your tsconfig.json: move the parameter inside angularCompilerOptions "angularCompilerOptions": { ..., "strictTemplates": true, ... } Angular >= 9 is necessary. More info here: https://angular.io/guide/template-typecheck.
This template uses typical HTML elements like <h2> and <p> , and also includes Angular template-syntax elements, *ngFor , {{hero.name}} , (click) , [hero] , and <app-hero-detail> . The template-syntax elements tell Angular how to render the HTML to the screen, using program logic and data.
Since Angular 9 the solution is strictTemplates
flag of Angular compile options, see Strict mode section of Template type checking guide. Enable the flag in tsconfig.json
file:
{ ... "compilerOptions": { ... }, "angularCompilerOptions": { "strictTemplates": true ... } }
Original answer:
Unfortunately, It seems that current Angular version doesn't check types of component inputs and events. You can use AOT compilation and enable fullTemplateTypeCheck angular compiler option, which performs some template type checking.
Enable fullTemplateTypeCheck option in src/tsconfig.app.json
{ "compilerOptions": { ... }, "angularCompilerOptions": { "fullTemplateTypeCheck": true ... } }
And build (or serve) your project with --aot
option
ng build --aot
What about inputs and events type checking, I found two issues on angular bug tracker (issue1 and issue2). As I understand, the solution of the problem depends on renderer implementation, and more likely that the problem may be fixed in next version of angular renderer, called Ivy. Here is feature request for inputs type checking in ivy renderer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With