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

时间:2019-12-02 16:31:30

标签: angular typescript

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

  

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

此代码出现在“ name.length”上,我希望该功能仅在字符串“ name”的长度大于或等于3个字符时才起作用。

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

要添加的两件事-

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

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