【问题标题】:Property Does Not Exist on TypeOf, Understanding Classes BetterTypeOf 上不存在属性,更好地理解类
【发布时间】:2022-01-03 05:27:20
【问题描述】:

我一直在学习课程和 TypeScript,遇到了一个我不明白的错误 - 希望有人可以帮助我。

我已经创建了如下界面:

export default interface IServerApi {
  url: string
  call: string
}

然后我创建了一个应该使我的 apicalls 成为这样的类:

class ApiCall implements IServerApi {
  public url: string
  public call: string

  constructor(apiUrl: string, apiEndpoint: string) {
    this.url = process.env.REACT_APP_SERVER_URL as string
    this.call = "products"
  }

  static async getAll() {
    const response = await fetch(`${this.url}/${this.call}`)
    const data = await response.json()
    return data
  }
}

但是,我在 this.url 下面收到一个 TS 错误,并显示以下消息:

any
Property 'url' does not exist on type 'typeof ApiCall'.ts(2339)

谁能指出这里发生了什么?我认为 this.url 会引用构造函数中设置的 url,然后我可以将类似 this.url 的内容传递给方法。目标是能够调用 ApiCall.getAll() 而不是重写 fetch。

谢谢!

【问题讨论】:

  • getAll 是静态的,url 在实例上。
  • 是时候做更多关于静态的阅读了。谢谢!

标签: javascript reactjs typescript


【解决方案1】:

问题与状态方法调用有关,getAll 方法是静态的,静态方法没有这个引用。

有3个解决方案

  1. 从 getAll 中删除静态 async getAll()
  2. 在 URL 中添加静态关键字。 public static url
  3. 创建当前类的实例并使用
    const instance = new ApiCall("", "");
    const response = await fetch(`${instance.url}/${this.call}`);

针对您的问题推荐:

    export default interface IServerApi {
      url: string
      call: string
    }
    
    class ApiCall implements IServerApi {
      public static url: string = process.env.REACT_APP_SERVER_URL as string
      public call: string
    
      constructor(apiUrl: string, apiEndpoint: string) {
        this.call = "products"
      }
    
      static async getAll() {
        const response = await fetch(`${ApiCall.url}/${this.call}`)
        const data = await response.json()
        return data
      }
    }

【讨论】:

  • @MarioCarbonell 我又添加了 1 种方法来解决这个问题
  • 哇,这真是太棒了!哈哈,这就是我最终要尝试的。使用多种不同的方法(get、post、put、delete)创建一个类 ApiCall,这样我就可以创建一个新的 ApiCall 并传递我需要的东西!太棒了!
猜你喜欢
  • 2021-01-09
  • 1970-01-01
  • 2019-03-19
  • 2020-10-04
  • 2020-08-19
  • 2017-11-06
  • 2018-11-09
  • 2018-04-26
  • 1970-01-01
相关资源
最近更新 更多