Promise参数类型不可分配

时间:2018-02-17 20:05:40

标签: javascript angular typescript es6-promise typescript-typings

我在Angular组件类上有以下方法:

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

      });
  }

这是使用的类型:

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

但是我收到了这个错误:

  

src / app / shared / services / utils-service.ts(57,13)中的错误:错误   TS2345:类型&#39;(代码:字符串)=&gt;的参数承诺| {url:   串;代码:字符串; pluginName:any; pluginType:any; ...&#39;不是   可分配给类型&#39;(值:字符串)=&gt;的参数   PromiseLike&#39 ;.输入&#39;承诺| {url:string;码:   串; pluginName:any; pluginType:any;插件:任何; }&#39;不是   可分配给类型&#39; PromiseLike&#39;。       输入&#39; {url:string;代码:字符串; pluginName:any; pluginType:any;插件:任何; }&#39;不能分配类型&#39; PromiseLike&#39;。         物业&#39;然后&#39;类型&#39; {url:string;代码:字符串; pluginName:any; pluginType:any;插件:任何; }&#39;

我无法弄清楚这个错误意味着什么。

1 个答案:

答案 0 :(得分:1)

您收到此错误是因为您的错误返回Promise而非string

我建议将所有return new Promise替换为throw new Error。然后,您可以使用.catch来处理错误,只需返回SCEPluginElement而不是SCEPluginElement | string