javascript - ' promise <void >' is not assignable to type ' promise <IListItem[]>

标签 javascript reactjs typescript promise

我有以下错误:

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

关于javascript - ' promise <void >' is not assignable to type ' promise <IListItem[]>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47249008/

相关文章:

javascript - 根据对象属性创建数组

javascript - 搜索引擎可以读取jquery操作吗

reactjs - 如何使用带有 typescript 的手动模拟, react 和开玩笑?

javascript - React Pixi 响应式阶段

javascript - 检查 Angular 中的 "mode"可见打印还是隐藏打印

reactjs - reducer 中存储的 ref 对象,没有 offsetTop 属性

javascript - 尽可能创建最简单的 typescript 定义文件

javascript - 提交 ajax 表单并停留在同一页面上不起作用

javascript - 按字段值对数组中的对象进行排序(如果存在)

javascript - 从无状态子组件更改父组件的状态