Search code examples
reactjstypescriptappwrite

appwrite web sdk with typescript


I am using demo-todo-with-react with typescript. For api.js creating api.tsx it gives me error on api.sdk={database,account} "Type '{database: Database; account: Account;}' is not assignable to type 'null' "

let api = {
  sdk: null,

  provider: () => {
    if (api.sdk) {
      return api.sdk;
    }
    let appwrite = new Appwrite();
    appwrite.setEndpoint(Server.endpoint).setProject(Server.project);
    const account = new Account(appwrite);
    const database = new Databases(appwrite);

    api.sdk = { database, account };
    return api.sdk;
  }
}

Thanks in advance


Solution

  • Add a custom type for the api object. In your case it would be something like this.

    interface AnyApi {
     sdk: null | any;
     provider: () => any;
    }
    
    
    let api: AnyApi = {
    ...
    }
    

    This would work.

    If you want to go fowreder add a template like this.

    interface AnyApi<T> {
     sdk: null | T;
     provider: () => T;
    }
    
    interface AppWriteSdk {
     database: Database;
     account: Account;
    }
    
    let api: AnyApi<AppWriteSdk>= {
    ...
    }