React.ForwardRef loses infer type of generic type
Asked Answered
D

0

6

I'm using React, and in this case the feature React.forwardRef.
The problem I'm having is that, after using the React.forwardRef, I lose the inferred type of a generic type T when using the component that is wrapped by React.forwardRef.

Let me explain with an example; take this code:

interface IUser {
    nickname: string;
}

interface IList<TRecord> {
    items: TRecord[];
    children: (item: TRecord) => React.ReactElement;
}

export const List = <TRecord extends unknown>(props: IList<TRecord>) => {
    return (
        <ul>
            {props.items.map(x => <li>{props.children(x)}</li>)}
        </ul>
    );
}

export const MyApp = () => {
    const items : IUser[] = [];
    return (
        <List items={items}>
            {item => <p>{item.nickname}</p>}
        </List>
    );
}

When I write {item.nickname} inside the return of MyApp, TypeScript can infer the type of item based on the props items passed to <List>.

enter image description here

Now, let me wrap List with React.forwardRef, like so:

export const List = React.forwardRef(<TRecord extends unknown>(props: IList<TRecord>, ref: any) => {
    return (
        <ul>
            {props.items.map(x => <li>{props.children(x)}</li>)}
        </ul>
    );
});

Here's what TypeScript tells me:

enter image description here

As you can see, TypeScript cannot infer anymore the type of item. What I think is happening is that, using React.forwardRef, I'm losing the genericness passed via the props items.. But I have no idea how I could fix this.

Doornail answered 25/11, 2021 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.