【发布时间】:2020-05-13 19:27:31
【问题描述】:
type ButtonVariant = 'action' | 'hero';
type Size = 'small' | 'medium' | 'large';
export interface ButtonProps {
variant: ButtonVariant;
size?: Size;
}
export default function Button(props: ButtonProps): ReactElement {
const { variant } = props;
if (variant === 'hero')) {
return <HeroButton {...props} />;
}
if (variant === 'pill') {
return <PillButton {...props} />;
}
}
在上面的代码中,我有两个 React 按钮的变体:HeroButton 和 PillButton。
两个按钮都期望“ButtonProps”作为它们的道具类型。但是,我想让 HeroButton only 期望大小为“中”或“大”。 PillButton 应该接受“小”、“中”或“大”作为其大小属性。
问题:我如何编写ButtonProps 接口,使得Button 组件允许(并在VS Code 中建议)'small' | 'medium' | 'large' 作为尺寸道具,当变量道具为“药丸”时",但只允许 'medium' | 'large' 变体道具是“英雄”?
注意:我已经研究过 TypeScript Discriminate Unions 来解决这个问题,但还没有成功。
【问题讨论】:
标签: reactjs typescript