1

Recently, I encountered some issues while using React. when I called my react generic component, BaseBlock.

I had already provided a type, but TypeScript threw an error saying

Expected 0 type arguments, but got 1.ts(2558)

I would like to ask how to solve this situation.

const items = ['test1', 'test2', 'test3'];
const renderComp = (item: any) => {
  return <div>{item}</div>
}
<BaseBlock<string> items={items}>{renderRow}</BaseBlock>
           ^
           error

This is my BaseBlock component

import React from 'react';

interface Props<T> {
  id?: string;
  items?: T[];
  children?: (item: T, index: number) => React.ReactNode;
  parentId?: string;
  contentId?: string[];
}

const BaseBlock = React.forwardRef(function BaseBlock<T>(
  { items, children }: React.PropsWithChildren<Props<T>>,
  ref: React.ForwardedRef<HTMLDivElement>
): React.ReactElement | null {
  return (
    <div data-testid="base-block" ref={ref}>
      {items && children && items.map(children)}
    </div>
  );
});

export type BaseBlockProps<T> = React.PropsWithRef<Props<T>>;

export default BaseBlock;

I give my component string type. Excepted no error and render this component. It just render, but typescript give me error

Expected 0 type arguments, but got 1.ts(2558)

I think it is that I give the <string> type for my comp, but this comp should not use type, it excepted 0 argument on this comp, so how can I solved?

Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38
fufu_shih
  • 11
  • 1
  • It’s the forwardRef which is making the component not generic. There are some workarounds — search for questions about using generics with forwardRef (or with memo, which has the same issues) – Linda Paiste Feb 19 '23 at 05:59

1 Answers1

0

I solved this problem by @Linda Paiste comment and reference this question.

Finally, I used global type augmentation and solved it.

declare module 'react' {
  function forwardRef<T, P = {}>(
    render: (props: P, ref: React.Ref<T>) => React.ReactElement | null
  ): (props: P & React.RefAttributes<T>) => React.ReactElement | null;
}
fufu_shih
  • 11
  • 1