将 forwardRef 与泛型一起使用时,我得到Property 'children' does not exist on type 'IntrinsicAttributes'or 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 …Run Code Online (Sandbox Code Playgroud) 我经常需要定义一个类型对象,其中只有当该类型的另一个属性是某个值时才接受属性键。
\n\n一个简单的例子(在 React 的上下文中,但应该适用于任何情况)是我需要一个Button接受以下属性的类型对象:
type Button = {\n size: 'small' | 'large';\n appearance: 'solid' | 'outline' | 'minimal';\n isDisabled?: boolean;\n hasFancyOutline?: boolean;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n现在,我实际上不希望类型接受hasFancyOutlineif appearanceis notoutline和isDisabledis false。
正确的方法是:
\n\ntype SharedButtonProps = {\n size: 'small' | 'large';\n}\n\ntype NonOutlineButtonProps = SharedButtonProps & {\n appearance: solid' | 'minimal';\n isDisabled?: boolean;\n}\n\ntype OutlineButtonProps = SharedButtonProps & {\n appearance: 'outline';\n isDisabled: false;\n hasFancyOutline?: boolean;\n}\n\ntype Button = NonOutlineButtonProps | OutlineButtonProps\nRun Code Online (Sandbox Code Playgroud)\n\n我想编写一个名为的速记实用程序类型ConditionalProps …