【问题标题】:Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '(controlName: string) => boolean'元素隐式具有 \'any\' 类型,因为类型 \'string\' 的表达式不能用于索引类型 \'(controlName: string) => boolean\'
【发布时间】:2022-11-10 18:23:22
【问题描述】:
hasError(typeofvalidator:string, controlname:string) : boolean 
{
    return this.CustomerModel.formCustomerGroup.contains[controlname].hasError(typeofvalidator);
 }

我正在学习 Angular,课程中的视频具有相同的代码,但它正在课程中运行,但出现错误。我不知道我做错了什么需要帮助。

【问题讨论】:

  • 仅供参考:Angularjs 是以前的版本......如果不是祖先和不同的包......而不是 Angular。您应该将标签从 Angularjs 更改为 Angular。
  • 回复:“在课程视频中有相同的代码”:你确定吗?您发布的代码没有多大意义。我强烈怀疑你抄错了什么。
  • 我附上了课程中的代码图片

标签: angular typescript


【解决方案1】:

也许尝试用普通括号() 替换contains 之后的方括号[]?看起来错误表明您正在尝试索引函数。

所以应该看起来更像这样:

return this.CustomerModel.formCustomerGroup.contains(controlname).hasError(typeofvalidator);

在此之后,我假设您的初始错误将得到解决,但可能还有另一个错误。

【讨论】:

  • 获取Property 'hasError' does not exist on type 'boolean'
  • @GunasekaranS 是的,因为contains 返回boolean。您必须在 FormControlFormGroupAbstractControl 对象上调用 hasError。我建议重构您的代码,使其看起来像这样:return this.formGroup.get('formControlName').hasError('errorType'); 请注意,这行代码中的 formGroup 指的是一个 FormGroup 对象,该对象内部有一个 FormControl,在此示例中名为“formControlName” .
【解决方案2】:

要对此进行调试,请将每个步骤分解为几个强类型变量。

hasError(typeofvalidator:string, controlname:string) : boolean 
{
  const customerModel: {formerCustomerGroup: string} = this.CustomerModel;

  const fCG: string = customerModel.formCustomerGroup;

  return fCG.contains[controlname].hasError(typeofvalidator);
}

我不知道为什么您的不起作用,而且我确信无论出于何种原因您的不起作用,我的也不会起作用,但是它将问题分解为一个非常可识别的位置,然后您可以从那里工作。

修复后,您可以根据需要将其改回较短的版本,但在这里您遇到了障碍,是时候进行搜索了。

好狩猎!

【讨论】:

  • 谢谢 !仍在寻找解决方案
  • 是的,你的也不行
  • 我刚刚意识到 string.prototype.contains 返回一个布尔值。并且布尔值没有 hasError 方法。
  • @JSmart523:但是这段代码没有调用contains,它正在检索contains 的动态指定属性。 (这对我来说似乎很奇怪,但也许在原始代码中有意义?)
【解决方案3】:

这就是问题

hasError(typeofValidator: string, controlname: string): boolean { 返回 this.customerModel.formCustomerGroup.controls[controlname].hasError(typeofValidator); }

解决方案

只需将 controlname 替换为 ControlName。

hasError(typeofValidator: string, controlName: string): boolean { 返回 this.customerModel.formCustomerGroup.controls[controlName].hasError(typeofValidator); }

【讨论】:

    【解决方案4】:

    它不包含。你应该改用控件试试这个

    返回 this.NewCustomer .FormCustomerGroup .controls[控制名称] .hasError(TypeOfValidator);

    【讨论】:

      猜你喜欢
      • 2019-11-24
      • 2020-11-14
      • 2021-12-24
      • 2023-01-09
      • 2021-10-24
      • 2023-01-09
      • 2022-01-17
      • 2022-09-23
      • 2022-10-08
      相关资源
      最近更新 更多