wrahim
wrahim

Reputation: 1168

Property does not exist in the type of class which implements an interface, compiler error

In an app using TypeScript I am running into this problem that I am not sure how to solve or why it is happening.

In a module I have this type of code

// Api.ts
interface ApiInterface {
  signIn(user: object): AxiosPromise
  authenticated(): AxiosPromise
  getCurrentUser(): AxiosPromise
}

export class Api implements ApiInterface {
  public signIn() {
     ...
  }

  public authenticated() {
     ...
  }

  public getCurrentUser() {
     ...
  }    
}

But the problem is that I get a compilation error when in another file I try to use Api class like this:

import { Api } from './Api'

async function foo() {
  const isAuthenticated = await Api.authenticated() // ERROR
  ...
}

The error states that: Property 'authenticated' does not exist on type 'typeof Api'.

How do I get past this? Does the compiler not know that class Api implements ApiInterface?

Upvotes: 0

Views: 1830

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250056

You are importing the class Api the member authenticated exists on an instance of the class. You need to create an instance using the new operator

import { Api } from './Api'

async function foo() {
  const api = new Api();
  const isAuthenticated = await api.authenticated() // ERROR
  ...
}

Upvotes: 4

Related Questions