簡體   English   中英

&#39;諾言 <void> &#39;不可分配給&#39;Promise <IListItem[]>

[英]'Promise<void>' is not assignable to type 'Promise<IListItem[]>

我有以下錯誤:

[ts]
Type 'Promise<void>' is not assignable to type 'Promise<IListItem[]>'.
  Type 'void' is not assignable to type 'IListItem[]'.
(method) Promise<{
    value: IListItem[];
}>.then<void>(onFulfilled?: (value: {
    value: IListItem[];
}) => void | Thenable<void>, onRejected?: (error: any) => void | Thenable<void>): Promise<void> (+2 overloads)

在下面的代碼中,我缺少什么?

import { SPHttpClient, SPHttpClientResponse } from "@microsoft/sp-http";
import { IWebPartContext } from "@microsoft/sp-webpart-base";
import { IListItem} from "./models/IListItem";
import { IFactory } from "./IFactory";
import { INewsListItem } from "./models/INewsListItem";
import { IDirectoryListItem } from "./models/IDirectoryListItem";
import { IAnnouncementListItem } from "./models/IAnnouncementListItem";

export class ListItemFactory implements IFactory {
    private _listItems: IListItem[];
    public getItems(requester: SPHttpClient, siteUrl: string, listName: string): Promise<IListItem[]> {
        switch(listName) {
            case "GenericList":
                let items: IListItem[];
                // tslint:disable-next-line:max-line-length
                return requester.get(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=Title,Id,Modified,Created,Author/Title,Editor/Title&$expand=Author,Editor`,
                SPHttpClient.configurations.v1,
                {
                    headers: {
                        "Accept": "application/json;odata=nometadata",
                        "odata-version": ""
                    }
                })
                .then((response: SPHttpClientResponse): Promise<{ value: IListItem[] }> => {
                    return response.json(); 
                })
                .then((json: { value: IListItem[] }) => {
                    console.log(JSON.stringify(json.value));
                    items=json.value.map((v,i)=>({ 
                        key: v.id,
                        id: v.id,
                        title: v.title,
                        created: v.created,
                        createdby: v.Author.Title,
                        modified: v.modified,
                        modifiedby: v.Editor.Title                        
                    }));

更新1:

上述方法的使用者:

 // read items using factory method pattern and sets state accordingly
  private readItemsAndSetStatus(): void {
    this.setState({
      status: "Loading all items..."
    });

    const factory: ListItemFactory = new ListItemFactory();
    factory.getItems(this.props.spHttpClient, this.props.siteUrl, this.props.listName)
    .then((items: IListItem[]) => {
      const keyPart: string = this.props.listName === "GenericList" ? "" : this.props.listName;
        // the explicit specification of the type argument `keyof {}` is bad and
        // it should not be required.
        this.setState<keyof {}>({
          status: `Successfully loaded ${items.length} items`,
          ["Details" + keyPart + "ListItemState"] : {
            items
          },
          columns: buildColumns(items)
        });
    });
  }

then您的回調將分配給全局items變量,但不會返回任何值-因此,promise將使用undefined解析。 您需要使用

.then((json: { value: IListItem[] }) => {
    console.log(JSON.stringify(json.value));
    return json.value.map((v,i) => ({
//  ^^^^^^
        key: v.id,
        id: v.id,
        title: v.title,
        created: v.created,
        createdby: v.Author.Title,
        modified: v.modified,
        modifiedby: v.Editor.Title                        
    }));
});

TypeScript型'承諾<void | object> ' 不可分配給類型 'Promise<object> ' 在 Promise.then()<div id="text_translate"><p> 我目前正在嘗試以 base64 格式實現緩存文檔的服務。 我希望這個服務從 sessionStorage 中獲取文檔,如果 sessionStorage 中沒有文檔,則從 IRequestService 中獲取它,然后將其保存到 sessionStorage。 我嘗試了這種方法,但出現類型錯誤</p><pre>Type 'Promise&lt;void | GetDocumentResult&gt;' is not assignable to type 'Promise&lt;GetDocumentResult&gt;'.</pre><p> 代碼如下所示:</p><pre> getDocument(requestId: string, documentId: DocumentID, requestService: IRequestService): Promise&lt;GetDocumentResult&gt; { if (this.storageKey in sessionStorage) { const documentsMap: Map&lt;DocumentID, GetDocumentResult&gt; = new Map(JSON.parse(sessionStorage.getItem(this.storageKey).)) if (documentsMap.get(documentId).== undefined) { return new Promise(resolve =&gt; resolve(documentsMap,get(documentId).)) } } return requestService.getDocument(requestId, documentId) .then(value =&gt; {this.setDocument(documentId, value)}) }</pre><p> 我期待 Promise&lt;GetDocumentResult&gt;.then 的返回類型是 Promise&lt;GetDocumentResult&gt;,但由於某種我不明白的原因,它是 Promise&lt;void | 獲取文檔結果&gt;</p><p> 有人知道為什么會這樣嗎?</p><p> 謝謝</p></div></object></void>

[英]TypeScript Type 'Promise<void | Object>' is not assignable to type 'Promise<Object>' on Promise.then()

暫無
暫無

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

相關問題 打字稿:類型&#39;Promise &lt;{}&gt;&#39;不能分配給&#39;Promise&#39; <void> “ 打字稿:輸入“承諾”<void> &#39; 不可分配給類型 &#39;void | 破壞者 TypeScript型'承諾<void | object> ' 不可分配給類型 'Promise<object> ' 在 Promise.then()<div id="text_translate"><p> 我目前正在嘗試以 base64 格式實現緩存文檔的服務。 我希望這個服務從 sessionStorage 中獲取文檔,如果 sessionStorage 中沒有文檔,則從 IRequestService 中獲取它,然后將其保存到 sessionStorage。 我嘗試了這種方法,但出現類型錯誤</p><pre>Type 'Promise&lt;void | GetDocumentResult&gt;' is not assignable to type 'Promise&lt;GetDocumentResult&gt;'.</pre><p> 代碼如下所示:</p><pre> getDocument(requestId: string, documentId: DocumentID, requestService: IRequestService): Promise&lt;GetDocumentResult&gt; { if (this.storageKey in sessionStorage) { const documentsMap: Map&lt;DocumentID, GetDocumentResult&gt; = new Map(JSON.parse(sessionStorage.getItem(this.storageKey).)) if (documentsMap.get(documentId).== undefined) { return new Promise(resolve =&gt; resolve(documentsMap,get(documentId).)) } } return requestService.getDocument(requestId, documentId) .then(value =&gt; {this.setDocument(documentId, value)}) }</pre><p> 我期待 Promise&lt;GetDocumentResult&gt;.then 的返回類型是 Promise&lt;GetDocumentResult&gt;,但由於某種我不明白的原因,它是 Promise&lt;void | 獲取文檔結果&gt;</p><p> 有人知道為什么會這樣嗎?</p><p> 謝謝</p></div></object></void> Promise 參數類型不可分配 angular2 TS2322類型&#39;Promise <void> &#39;不可分配給&#39;Promise <string> &#39;當給定字符串時 RxDB Angular2-cli&#39;承諾 <void> &#39;不能賦值給&#39;Promise&#39;類型的參數 <any> “ 打字稿:類型 &#39;Promise&lt;{}&gt;&#39; 不可分配給類型 反應 TS - 類型 '() =&gt; Promise<void> ' 不可分配給類型 'EventHandler<clickevent, boolean | void> '</clickevent,></void> TS2322:類型&#39;(數據:TicketFullDTO)=&gt; 承諾<void> &#39; 不能分配給類型 &#39;FormEventHandler<HTMLFormElement> &#39; 輸入&#39;承諾<UserDomain> []&#39; 不可分配到類型 &#39;UserrDomain[]&#39;
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM