我一直在尝试学习类(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种解决方案
- 从 getAll 中删除静态
async getAll()
- 在网址中添加静态关键字。
公共(public)静态网址
- 创建当前类的实例并使用
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/