Search code examples
javascriptangulartypescriptes6-promisetypescript-typings

Promise argument type is not assignable


I have the following method on an Angular component class:

getPluginViaUrl(url: string): Promise<SCEPluginElement | string> {

    const self = this;

    return fetch(url, {cache: 'no-store'}).then(function (result) {
        return result.text();
      })
      .then(function (code) {

        const result = self.evalPluginCode(code);

        if (!result.SCEPlugin) {
          return Promise.reject('No SCEPlugin property exported from supposed plugin.');
        }

        if (!result.SCEPlugin.pluginName) {
          return Promise.reject('SCEPlugin is missing a name (missing "pluginName" field)');
        }

        if (!result.SCEPlugin.pluginType) {
          return Promise.reject('SCEPlugin is missing a type (missing "pluginType" field).');
        }


        return {
          url: url,
          code: code,
          pluginName: result.SCEPlugin.pluginName,
          pluginType: result.SCEPlugin.pluginType,
          plugin: result.SCEPlugin
        };

      });
  }

here is the type being used:

export interface SCEPluginElement {
  url: string,
  code: string,
  pluginName: string,
  pluginType: string,
  plugin: Object
}

but I am getting this error:

ERROR in src/app/shared/services/utils-service.ts(57,13): error TS2345: Argument of type '(code: string) => Promise | { url: string; code: string; pluginName: any; pluginType: any;...' is not assignable to parameter of type '(value: string) => PromiseLike'. Type 'Promise | { url: string; code: string; pluginName: any; pluginType: any; plugin: any; }' is not assignable to type 'PromiseLike'. Type '{ url: string; code: string; pluginName: any; pluginType: any; plugin: any; }' is not assignable to type 'PromiseLike'. Property 'then' is missing in type '{ url: string; code: string; pluginName: any; pluginType: any; plugin: any; }'.

I cannot figure out what this error means.


Solution

  • You're receiving this error because you are returning Promises for your errors and not strings.

    I'd suggest replacing all return new Promise with throw new Error. Then you can use .catch to handle the errors and simply return a SCEPluginElement instead of SCEPluginElement | string.