javascript - react 类型错误 "not assignable to parameter of type ' never'"

标签 javascript reactjs typescript

我想要做的是遍历当前的 posttype 和“产品”,但我正在努力处理这些类型。所以我收到以下错误:

Argument of type 'Record<string, any>[]' is not assignable to parameter of type 'never'.


在这部分:
...pages.map((page) => ({
我的代码:
  const pages = useSelect((select) => {
    const editor = select("core/editor");
    const currentPostType: string = editor.getCurrentPostType();
    const selectablePostTypes = [currentPostType, "products"];

    const postList = [];

    selectablePostTypes.forEach((singlePostType) => {
      const records: Record<string, any>[] = select("core").getEntityRecords(
        "postType",
        singlePostType
      );

      postList.push(records);
    });
  });

  // Make dropdown of pagesOptions
  const pagesOptions = [
    ...[
      {
        value: "0",
        label: __("No page selected", "demosite"),
      },
    ],
    ...pages.map((page) => ({
      value: page.id,
      label: page.title,
    })),
  ];
添加有效的代码:
  const pages = useSelect((select) => {
    const editor = select("core/editor");
    const postType: string = editor.getCurrentPostType();
    const records: Record<string, any>[] = select("core").getEntityRecords(
      "postType",
      postType
    );

    return records
      ? records.map((record) => ({
          description: record.description,
          id: record.id,
          featuredMedia: record.featuredMedia,
          link: record.link,
          subtitle: record.subtitle,
          title: record.title.rendered,
        }))
      : [];
  });
这里它针对一种帖子类型,即您当前正在编辑的帖子类型,但我想在一些帖子类型上循环。
例子:
const selectablePostTypes = ['page', 'post', 'product'];

最佳答案

这是您对 postList 的初始化

const postList = [];
因为您没有为 typescript 提供任何值来“找出”应该属于该数组的内容的类型签名,所以它将其设置为
never[]
这意味着它禁止您向该空数组添加任何值。在此处添加类型
const postList: Record<string, any>[][] = [];

关于javascript - react 类型错误 "not assignable to parameter of type ' never'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69220780/

相关文章:

javascript - 访问路由端点之外的 req 属性

javascript - 在 React-Native 中制作指南针

typescript - 为什么 Visual Studio Code 命令面板中没有出现 Typescript 命令?

asp.net - VS 2015 和 msbuild 抑制 typescript 错误

angular - 更新 Angular 和 CLI 导致 : Incompatible peer dependencies found

javascript - 将 JSON(jQuery) 发送到 PHP 并对其进行解码

javascript - Meteor.users.update() 不适用于注销+登录

reactjs - Enzyme,如何访问通过 props 传递的组件

reactjs - 使用 Jest 测试 React 组件会出现 'Cannot find module' 错误

javascript - 使用 Javascript 更改页面中与某个正则表达式匹配的链接