2

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?

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) Commented Feb 19, 2023 at 5:59

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.