Angular 2模板中的类型检查 [英] Type checking in Angular 2 templates
问题描述
我们正在Angular 2和TypeScript中构建一个应用程序.我们尝试在可能的情况下静态检查类型.有什么方法可以检查模板中的类型?考虑以下片段:
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>
假定Foo
组件中的data
具有某种类型TData
.但是,默认情况下,没有什么阻止我传递不符合TData
的dataObj
的. Angular模板是否有打字稿扩展名,可以在这种情况下验证类型?
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?
推荐答案
由于Angular 9解决方案是Angular编译选项的strictTemplates
标志,请参见严格模式部分noreferrer>模板类型检查指南.启用tsconfig.json
文件中的标志:
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
...
}
}
原始答案:
不幸的是,当前的Angular版本似乎不检查组件输入和事件的类型.您可以使用 AOT 编译并启用
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.
在src/tsconfig.app.json
{
"compilerOptions": { ... },
"angularCompilerOptions": {
"fullTemplateTypeCheck": true
...
}
}
并使用--aot
选项构建(或服务)您的项目
And build (or serve) your project with --aot
option
ng build --aot
关于输入和事件类型检查呢,我在角度错误跟踪器上发现了两个问题( issue1 和 issue2 ).据我了解,问题的解决方案取决于渲染器的实现,并且更有可能在下一版本的角度渲染器(称为这是功能请求,用于在常春藤渲染器中检查输入类型.
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.
这篇关于Angular 2模板中的类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!