Repository navigation
Closed
Labels
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
Reacted by Pavel Belyaev and Andrew
Activity
Andarist commentedon Aug 1, 2024
I think it bisects to #58008 , it looks similar to #59108 but it wasn't fixed by #59121
This is a bug - the conditional type stays deferred here but it shouldn't.
A slimmed down repro case can be seen here (TS playground):
It can also be reproduced with the code from #59108 after adding a default type parameter to the wrapped generic function (TS playground):