【问题标题】:TS2339: Property 'length' does not exist on type 'never'TS2339:“从不”类型上不存在属性“长度”
【发布时间】:2020-03-27 07:25:17
【问题描述】:

我是 angular 和 typescript 的新手,遇到了这个错误

TS2339:“从不”类型上不存在属性“长度”。

它出现在“name.length”的此代码片段中,我希望该函数仅在字符串“name”的长度大于或等于 3 个字符时才起作用。

  processForm() {
   if(name.length>=3){
    const allInfo = `My name is ${this.name}....`;
    alert(allInfo);
   }
  }

【问题讨论】:

  • 代码中有用户never

标签: angular typescript


【解决方案1】:

要添加两件事 -

  1. 使用this.name 而不是name(如果它是类变量)
  2. 像这样添加对变量存在的检查 -

    processForm() {
      if(name && name.length>=3){
        const allInfo = `My name is ${this.name}....`;
        alert(allInfo);
      }
    }
    

【讨论】:

    【解决方案2】:

    如果name是组件或类中的属性/字段,则需要使用this.name而不是name

    【讨论】:

      猜你喜欢
      • 2020-11-06
      • 2021-05-18
      • 2016-03-14
      • 2017-02-25
      • 2021-10-05
      • 2021-11-24
      • 2019-01-11
      • 2021-05-08
      • 2021-10-15
      相关资源
      最近更新 更多