【问题标题】:Property does not exist error in TypeScript static methodTypeScript 静态方法中的属性不存在错误
【发布时间】:2020-10-31 00:13:01
【问题描述】:

下面是我的 TypeScript 代码。在静态方法中它会引发错误:

“typeof Person”类型上不存在属性“name”。

这个错误的原因是什么,我该如何解决?

class Person {
    name: string = 'no name'
    constructor(protected id: string,){
    }
    showId=():string => {
        return this.id
    }
    static showname(){return this.name}
}

【问题讨论】:

    标签: javascript html typescript


    【解决方案1】:

    您不能在静态上下文中访问类成员。 name 属性也需要是静态的。

    【讨论】:

      【解决方案2】:
      class Person {
          static name: string = 'no name'
          constructor(protected id: string,){
          }
          showId=():string => {
              return this.id
          }
          static showname(){return this.name}
      }
      

      或

      class Person {
          name: string = 'no name'
          constructor(protected id: string,){
          }
          showId=():string => {
              return this.id
          }
          static showname(person: Person){return person.name}
      }
      

      【讨论】:

        猜你喜欢
        • 2017-07-15
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多