javascript - TypeOf 上不存在属性,更好地理解类

标签 javascript reactjs typescript

我一直在尝试学习类(class)和 TypeScript,遇到了一个我不明白的错误 - 希望有人可以帮助我。

我创建了以下界面:

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

然后我创建一个类,该类应该使我的 APIcall 如下:

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() 而不是重写获取。

谢谢!

最佳答案

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

有3种解决方案

  1. 从 getAll 中删除静态 async getAll()
  2. 在网址中添加静态关键字。 公共(public)静态网址
  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
      }
    }

关于javascript - TypeOf 上不存在属性,更好地理解类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70561983/

相关文章:

reactjs - 在 useEffect React 中调用异步函数中的 Firebase v9 onSnapShot

javascript - React JS Rest Api 调用

javascript - 未捕获类型错误 : not a function for a private method in TypeScript

typescript - Typescript 可以确保数组具有重复的类型模式吗?例如[字符串,数字,字符串,数字,....(永远)]

javascript - lambda js : lens for deeply nested objects with nested arrays of objects

javascript - 我可以在 async.js forEach 中扩展迭代器函数吗?

javascript - onMouseOut 在没有鼠标离开 div 的情况下触发

javascript - 如何在 React.js 中的 localStorage 发生任何更改时立即更新状态

javascript - 尽管我的组件已在我的模块的 entryComponents 选项中声明,但 Angular 如何找不到该组件的组件工厂?

javascript - ie10 background-position-x 的解决方法