【发布时间】:2020-04-29 17:20:13
【问题描述】:
我正在尝试创建一个可以使用 3 个接口中的 1 个接口的组件,该组件能够根据传递给它的 props 来确定哪个接口。
interface CommonProps {
label: string;
icon?: React.ComponentType;
role?: string;
}
interface ButtonProps extends CommonProps {
handleOnClick: () => void;
selected?: boolean;
largeVariant?: boolean;
}
interface LinkProps {
to: string;
openInNewTab?: boolean;
}
interface HrefProps {
href: string;
openInNewTab?: boolean;
}
const Button: React.FC<ButtonProps | LinkProps | HrefProps> = props => {
const { label, handleOnClick, to, href, icon, openInNewTab } = props;
if (to || href) {
const Component = to ? Link : 'a';
return (
<StyledButton
component={Component}
target={openInNewTab ? '_blank' : undefined}
onMouseDown={(e: any) => {
href && pushMatomoExternalLink(e, href);
}}
{...props}
>
{icon && <StyledIcon icon={icon} />}
{label}
</StyledButton>
);
}
return (
<StyledButton onClick={handleOnClick} {...props}>
{icon && <StyledIcon icon={icon} />}
{label}
</StyledButton>
);
};
期望的行为,包括我希望看到的错误。
<Button label="View Report" handleOnClick={action('BUTTON CLICKED')} />
会推断接口是ButtonProps
<Button label="View Report" selected />
TypeScript 错误:类型“{”中缺少属性“handleOnClick” 标签:字符串; selected: boolean;}' 但在 'ButtonProps' 类型中是必需的。
<Button label="View Report" openInNewTab />
会推断该接口是 LinkProps 或 HrefProps
类型 '{ label: string; 中缺少属性 'to' openInNewTab:布尔值; }' 但在“LinkProps”类型中是必需的。
类型'{ label: string; 中缺少属性'href'; openInNewTab:布尔值; }' 但在 'HrefProps' 类型中是必需的。
<Button label="View Report" href="/" openInNewTab />
会推断出接口是HrefProps
【问题讨论】:
-
请考虑编辑代码以构成一个minimal reproducible example,该minimal reproducible example 可以拖放到The Playground 等独立IDE 中,以便其他人可以看到您的问题。现在我没有
Link或StyledButton的定义,所以我不确定我的建议是否适合你。我也不明白您所说的“推断”是什么意思;您希望编译器在哪里推断接口?编译器在这里的行为在我看来是合理的;您能否详细说明您的预期与正在发生的事情? -
感谢您的建议。下班后我会对示例进行一些更改。
标签: reactjs typescript