解析运行时Javascript属性的Typescript编译器消息
我有一段代码如下:解析运行时Javascript属性的Typescript编译器消息,javascript,angular,typescript,Javascript,Angular,Typescript,我有一段代码如下: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf="email.errors.required">Email is re
<div class="authentication-validation-message-container">
<ng-container *ngIf="email.invalid && (email.dirty || email.touched)">
<div class="validation-error-message" *ngIf="email.errors.required">Email is required.</div>
<div class="validation-error-message" *ngIf="email.errors.email">Email is not in the valid format. Please use a valid
email.
</div>
</ng-container>
<ng-container *ngIf="pwd.invalid && (pwd.dirty || pwd.touched)">
<div class="validation-error-message" *ngIf="pwd.errors.required">Password is required.</div>
</ng-container>
<div class="validation-error-message" *ngIf="!verdict">{{errorMessage}}</div>
</div>
电子邮件是必需的。
电子邮件的格式无效。请使用有效的密码
电子邮件。
密码是必需的。
{{errorMessage}}
如果您使用的是Angular,则可以使用类似于email.errors.required的代码检查输入中是否包含无效数据。但是,.required
、.email
等都是在JS的运行时执行期间出现的,因此在编译时TypeScript不知道这些
当我查看IDE(使用Jetbrains Rider,顺便说一句)时,我看到了这些编译时警告,我想用TypeScript惯用的方式来解决它们:
我已经尝试了(email.errors as any)。需要,但警告不会消失。我相信as
现在是推荐的铸造方法,而不是(实际的问题是预期存在的类型。ngIf
构造期望有一个带有布尔值的表达式,但在实际状态下,您的代码无法确保满足该要求。要使警告消失,您应该使用“?”
运算符安全导航或强制转换表达式设置为boolean
类型
例如,您可以执行以下操作:
<div class="validation-error-message" *ngIf="email?.errors.required">Email is required.</div>
<div class="validation-error-message" *ngIf="email?.errors.email">Email is not in the valid format. Please use a valid
需要电子邮件。
电子邮件格式无效。请使用有效的
警告说明了什么?@messervill立即查看新编辑。警告是否使用以下符号消失:*ngIf=“email[“errors”][“required”]
?将文本信息包括为文本,而不是图像。中的一个建议是使用“安全导航”操作符:电子邮件?。错误。必需的
。这就是问题所在,您的回答正确。不过很有意思。错误消息完全是误导性的。