【问题标题】:React type error "not assignable to parameter of type 'never'"反应类型错误“不可分配给'从不'类型的参数”
【发布时间】:2021-11-12 04:13:06
【问题描述】:

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

'Record[]' 类型的参数不能分配给'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'];

【问题讨论】:

  • 旁注:在那里你实际上有这个代码:const pagesOptions = [...[somevalue]],可以写成const pagesOptions = [somevalue]
  • 假设useSelect 是一种效果,const pages = useSelect 看起来不正确。更重要的是,您传递给 useSelect 的函数不会返回任何内容。
  • 能否请您提供 TS 操场上的最小可重现示例?

标签: javascript reactjs typescript


【解决方案1】:

这是你对postList的初始化

const postList = [];

因为您没有为 typescript 提供任何值来“找出”应该属于该数组的内容的类型签名,所以它将其设置为

never[]

这意味着它禁止您向该空数组添加任何值。在此处添加类型

const postList: Record<string, any>[][] = [];

【讨论】:

    猜你喜欢
    • 2019-12-19
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2021-10-18
    • 2019-10-17
    • 1970-01-01
    • 2019-06-24
    • 2021-06-14
    相关资源
    最近更新 更多