簡體   English   中英

Promise 參數類型不可分配

[英]Promise argument type is not assignable

我在 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:'(code: string) 類型的參數 => Promise | { 網址:字符串; 代碼:字符串; 插件名稱:任意; pluginType: any;...' 不能分配給類型為 '(value: string) => PromiseLike' 的參數。 輸入'承諾| { 網址:字符串; 代碼:字符串; 插件名稱:任何; 插件類型:任意; 插件:任何; }' 不可分配給類型 'PromiseLike'。 輸入 '{ url: 字符串; 代碼:字符串; 插件名稱:任意; 插件類型:任意; 插件:任何; }' 不可分配給類型 'PromiseLike'。 類型“{ url: string;”中缺少屬性“then” 代碼:字符串; 插件名稱:任意; 插件類型:任意; 插件:任何; }'。

我無法弄清楚這個錯誤意味着什么。

您收到此錯誤是因為您正在為錯誤返回Promise s 而不是string s。

我建議用throw new Error替換所有return new Promise 然后你可以使用.catch來處理錯誤並簡單地返回一個SCEPluginElement而不是SCEPluginElement | string SCEPluginElement | string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM