Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React type error "not assignable to parameter of type 'never'"

What I want to do is loop over current posttype and 'products' but I'm struggling with the types. So I got the following error:

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

On this part:

...pages.map((page) => ({

of my code:

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

Add the code which works:

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

Here it is targeted on one post type, the post-type you're currently editing, but I want to loop this over some posttypes.

Examples:

const selectablePostTypes = ['page', 'post', 'product'];
like image 240
Gurdt Avatar asked Sep 17 '21 09:09

Gurdt


1 Answers

It is your initialization of postList

const postList = [];

Because you haven't provided it any values for typescript to "figure out" the type signature of the content that should belong in that array, it sets it as

never[]

This means it bans you from adding any values to that empty array. Add a type here

const postList: Record<string, any>[][] = [];
like image 120
Andrew Avatar answered Nov 12 '22 03:11

Andrew