Sam*_*uel 6 javascript typescript reactjs
我试图根据是否传递特定道具有条件地扩展我的组件道具。
我的目标是通过anchorifhref传递的属性来扩展 props ,并通过buttonif的属性扩展。
这甚至可能吗?
难道不能将属性定义为联合类型并使用类型保护吗?像这样的东西:
type ButtonProps = { onClick: () => {} }
type LinkProps = { href: string }
type BaseProps = {
spinner?: boolean
}
type Props = BaseProps & (ButtonProps | LinkProps)
export const Button = (props: Props) => {
if ('href' in props) {
// Link
} else {
// Button
}
}
Run Code Online (Sandbox Code Playgroud)