角度模板是 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';
我的模板.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 参数创建这个元素的工厂(并且这个参数可以有类型信息)。