简体   繁体   English

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

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

I have the following error: 我有以下错误:

[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)

In the following piece of code, what am I missing? 在下面的代码中,我缺少什么?

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

Update 1: 更新1:

the consumer of the above method: 上述方法的使用者:

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

Your then callback assigns to a global items variable, but does not return any value - so the promise resolves with undefined . then您的回调将分配给全局items变量,但不会返回任何值-因此,promise将使用undefined解析。 You need to use 您需要使用

.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> “ - Typescript : Type 'Promise<{}>' is not assignable to type 'Promise<void>' 打字稿:输入“承诺”<void> &#39; 不可分配给类型 &#39;void | 破坏者 - Typescript: Type 'Promise<void>' is not assignable to type 'void | Destructor' 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() Promise 参数类型不可分配 - Promise argument type is not assignable angular2 TS2322类型&#39;Promise <void> &#39;不可分配给&#39;Promise <string> &#39;当给定字符串时 - angular2 TS2322 Type 'Promise<void>' is not assignable to type 'Promise<string>' when given a string RxDB Angular2-cli&#39;承诺 <void> &#39;不能赋值给&#39;Promise&#39;类型的参数 <any> “ - RxDB Angular2-cli 'Promise<void>' is not assignable to parameter of type 'Promise<any>' 打字稿:类型 &#39;Promise&lt;{}&gt;&#39; 不可分配给类型 - Typescript: Type 'Promise<{}>' is not assignable to type 反应 TS - 类型 '() =&gt; Promise<void> ' 不可分配给类型 'EventHandler<clickevent, boolean | void> '</clickevent,></void> - React TS - Type '() => Promise<void>' is not assignable to type 'EventHandler<ClickEvent, boolean | void>' TS2322:类型&#39;(数据:TicketFullDTO)=&gt; 承诺<void> &#39; 不能分配给类型 &#39;FormEventHandler<HTMLFormElement> &#39; - TS2322: Type '(data: TicketFullDTO) => Promise<void>' is not assignable to type 'FormEventHandler<HTMLFormElement>' 输入&#39;承诺<UserDomain> []&#39; 不可分配到类型 &#39;UserrDomain[]&#39; - Type 'Promise<UserDomain>[]' is not assignable to type 'UserrDomain[]'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM