-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Closed
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue
Milestone
Description
π Search Terms
react, forwardRef, component props, ComponentProps
π Version & Regression Information
- This changed between versions 5.4.5 and 5.5.5
β― Playground Link
π» Code
I don't know if it's strictly TypeScript issue or not (please let me know if I should report this elsewhere instead), but in v5.5.4 I noticed that type ComponentProps from React library doesn't work anymore when I use custom forwardRef (I use it so my generic components are typed correctly):
function forwardRef<T, P>(
component: (props: P, ref: Ref<T>) => React.ReactNode,
): (props: P & { ref?: Ref<T> }) => React.ReactNode {
return baseForwardRef(
component as unknown as ForwardRefRenderFunction<unknown, unknown>,
);
}
type ComponentWithForwardRefProps<T extends ElementType> =
ComponentPropsWithoutRef<T> & {
className?: string;
as?: T | undefined;
};
const ComponentWithForwardRef = forwardRef(
<T extends ElementType = "span">(
props: ComponentWithForwardRefProps<T>,
ref: Ref<HTMLElement>,
) => {
return null;
},
);
type Result2 = ComponentProps<typeof ComponentWithForwardRef>["className"]; // error here: `className` cannot be used to index type etc.
let result2: Result2 = "some-class-name"; // error here, obvisouslyWhen i remove the default value for type parameter T, it works again:
export const ComponentWithForwardRef = forwardRef(
<T extends ElementType>(
props: ComponentWithForwardRefProps<T>,
ref: Ref<HTMLElement>,
) => {
return null;
},
);
type Result2 = ComponentProps<typeof ComponentWithForwardRef>["className"]; // Result2 is `string | undefined`
let result2: Result2 = "some-class-name"; // no error
It also works if I remove the as props:
type ComponentWithForwardRefProps<T extends ElementType> =
ComponentPropsWithoutRef<T> & {
className?: string;
};I'm not sure if this is a regression, or if I'm doing something wrong, but I would be grateful to get some more info on this. Thank you.
π Actual behavior
Component props are not correctly inferred.
π Expected behavior
Same as in previous version of TypeScript.
Additional information about the issue
No response
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue