Skip to content

[@types/react] Error with forwardRef & children #48419

@MrJmpl3

Description

@MrJmpl3

When I try to use children of a component with forwardRef has the next error:

TS2322: Type '{ children: ReactNode; error: boolean; full: boolean; secondary: boolean; type: "submit" | "reset" | "button"; white: boolean; }' is not assignable to type 'IntrinsicAttributes & BaseButtonInnerProps & RefAttributes<HTMLButtonElement>'.   Property 'children' does not exist on type 'IntrinsicAttributes & BaseButtonInnerProps & RefAttributes<HTMLButtonElement>'.

The error is in the types:

interface ForwardRefRenderFunction<T, P = {}> {
        (props: PropsWithChildren<P>, ref: ((instance: T | null) => void) | MutableRefObject<T | null> | null): ReactElement | null;
        displayName?: string;
        // explicit rejected with `never` required due to
        // https://github.com/microsoft/TypeScript/issues/36826
        /**
         * defaultProps are not supported on render functions
         */
        defaultProps?: never;
        /**
         * propTypes are not supported on render functions
         */
        propTypes?: never;
}

function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;

That return a type of a component without children, but is you add the children in your props with PropsWithChildren , exists another problem.

The ForwardRefRenderFunction has a duplicate PropsWithChildren

Solution:

Exists 2 ways to solve this:

  1. Wrap PropsWithChildren to PropsWithoutRef<P>
  2. Remove PropsWithChildren of ForwardRefRenderFunction (the user need declare manually the PropsWithChildren in their components)

Autors: @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @DovydasNavickas @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @Hotell @franklixuefei @Jessidhia @saranshkataria @lukyth @eps1lon @zieka @dancerphil @dimitropoulos @disjukr @vhfmag @hellatan

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions