如何修复“"email"”类型的参数不可分配给 'string[]' 类型的参数错误?

How to fix Argument of type '"email"' is not assignable to parameter of type 'string[]' error?

Angular 5 应用程序工作正常,但在使用生产构建它时出现以下错误。它也可以用 ng build 构建,但不能用 ng build --prod.

Argument of type '"email"' is not assignable to parameter of type 'string[]'.

上线代码:

<mat-form-field>
  <input matInput placeholder="Email" formControlName="email" required>
  <mat-error *ngIf="form.hasError('email', 'email') && !form.hasError('required', 'email')">
    Please enter a valid email address
  </mat-error>
  <mat-error *ngIf="form.hasError('required', 'email')">
    Email is <strong>required</strong>
  </mat-error>
</mat-form-field>

和形式:

private createForm() {
  this.form = new FormGroup({
    email: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('', Validators.required)
  });
}

我认为您需要根据 Angular 的源代码 (line 520-526):

将第二个 'email' 参数包装在一个数组中
/**
 * Returns true if the control with the given path has the error specified. Otherwise
 * returns false.
 *
 * If no path is given, it checks for the error on the present control.
 */
hasError(errorCode: string, path?: string[]): boolean  { return !!this.getError(errorCode, path); }

我相信它在您的常规构建中实际工作的原因是因为尽管它在技术上是无效的,但最终执行的代码具有接受 Array<string|number> | string (line 37-56) 的调用签名。

function _find(control: AbstractControl, path: Array<string|number>| string, delimiter: string) {
    ...
}

注意:您的模板无法通过 non-AOT 模式下的输入系统 运行,因此在您进行 --prod 构建之前不会弹出.