Home > Software design >  Property Does Not Exist on TypeOf, Understanding Classes Better
Property Does Not Exist on TypeOf, Understanding Classes Better

Time:01-03

I've been playing around with learning classes and TypeScript, and I encountered an error I do not understand - hopefully someone can help me.

I've created the following interface:

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

And then I create a class that ought to make my apicalls as so:

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
  }
}

However,I get a TS error underneath this.url with the following message:

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

Can anyone point me to what's going on here? I thought that this.url would reference the url set in the constructor, and then I could pass something like this.url down into the methods. The goal would be to just be able to call ApiCall.getAll() instead of rewriting a fetch.

Thank you!

CodePudding user response:

The issue is related to a state method call, getAll method is static and static methods do not have this reference.

There are 3 solutions for this

  1. Remove static from getAll async getAll()
  2. Add static keyword in URL. public static url
  3. Create an instance of the current class and use
    const instance = new ApiCall("", "");
    const response = await fetch(`${instance.url}/${this.call}`);

Recommended for your problem:

    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
      }
    }
  • Related