将 forwardRef 与泛型一起使用时,我得到Property 'children' does not exist on type 'IntrinsicAttributes'
或Property 'ref' does not exist on type 'IntrinsicAttributes'
。
https://codesandbox.io/s/react-typescript-0dt6d?fontsize=14
上面 CodeSandbox 链接中的相关代码复制到这里:
interface SimpleProps<T extends string>
extends React.HTMLProps<HTMLButtonElement> {
random: T;
}
interface Props {
ref?: React.RefObject<HTMLButtonElement>;
children: React.ReactNode;
}
function WithGenericsButton<T extends string>() {
return React.forwardRef<HTMLButtonElement, Props & SimpleProps<T>>(
({ children, ...otherProps }, ref) => (
<button ref={ref} className="FancyButton" {...otherProps}>
{children}
</button>
)
);
}
() => (
<WithGenericsButton<string> ref={ref} color="green">
Click me! // Errors: Property 'children' does not exist on type 'IntrinsicAttributes'
</WithGenericsButton>
)
这里建议了一个潜在的解决方案,但不确定如何在这种情况下实施:https : //github.com/microsoft/TypeScript/pull/30215 (从https://stackoverflow.com/a/51898192/9973558找到)