使用自定义类型Angular验证输入

时间:2017-05-23 11:39:13

标签: angular typescript

我有一个组件,其输入被定义为自定义类型。

@Input() public labelSize: 'small' | 'normal' | 'large'  = 'normal';

但显然我可以将任何类型的参数传递给组件标记。我永远不会有任何错误/警告。

<my-component labelSize="whatever"></my-component>

我可以通过号码传递

<my-component labelSize=12345></my-component>

我希望打字稿编译器或角度来给我一些关于这种错误的反馈。

我应该验证自己所有组件输入的类型?

任何最佳做法?

由于

1 个答案:

答案 0 :(得分:1)

角度模板是HTML,并且不会以任何方式挂钩到typescript中以进行检查。甚至在打字稿中也允许绕过类型声明,例如this.labelSize = 'whatever' as any

最后代码仍然是javascript。在模板中就像从一开始就使用普通的javascript。

如果您真的希望预先发现错配,可以采用以下解决方案:

<强> 1。验证

如已经建议的那样,进行手动验证或使用验证库来指定约束,例如: https://validatejs.org/

顺便说一句,你也可以使用Pipe在你的任何值上动态添加验证,并在你的html上更清晰。

<强> 2。配置对象

您可以捕获类型在对象中重要的组件的配置,例如

@Input() public config: {
  labelSize: 'small' | 'normal' | 'large';
} = { labelSize: 'normal' }

然后将输入绑定到myCompConfig

<my-component [config]="myCompConfig"></my-component>

然后在您使用它的控制器中

this.myCompConfig = { labelSize: 'whatever' } // error <- type is enforced now

第3。模板的TS

您可以使用TS而不是HTML来模板,并使用某些类型信息来协助它:

首先分享您的类型

export type LabelSize = 'small' | 'normal' | 'large'

@Input() public labelSize: LabelSize = 'normal';

MY-template.ts

const labelSize: LabelSize = 'whatever' // error <- type is enforced 

export const template = `
    <my-component labelSize=${labelSize}></my-component>`
`;

然后在你的组件中直接使用它

import { template } from './my-template.ts';
@Component({ selector: 'something', template })

请注意,这也可以提取到工厂方法中,用于创建太阳穴的部分,例如:你可以有一个工厂来创建这个基于labelSize参数的元素(这个参数可以有类型信息)。