在 Angular 2 模板中进行类型检查 [英] Type checking in Angular 2 templates

查看:35
本文介绍了在 Angular 2 模板中进行类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在用 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.但是,默认情况下,没有什么可以阻止我传递不符合 TDatadataObj.是否有针对 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 开始,解决方案是 strictTemplates Angular 编译选项的标志,参见 严格模式 部分rel="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 编译并启用 fullTemplateTypeCheck 角度编译器选项,它执行一些模板类型检查.

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

关于输入和事件类型检查,我在 angular bug tracker 上发现了两个问题(issue1a> 和 issue2).据我了解,问题的解决方案取决于渲染器的实现,更有可能在下一版本的角度渲染器中解决该问题,称为 常春藤.这是 ivy 渲染器中输入类型检查的功能请求.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆