Type checking in Angular 2 templates

后端 未结 7 519
夕颜
夕颜 2021-02-02 06:07

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 fol

7条回答
  •  被撕碎了的回忆
    2021-02-02 06:29

    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.

提交回复
热议问题