ButtonProps 是否可以设置为button和a的联合类型?

来源:4-11 精益求精 - Buton 组件编码第二部分

李允鹰

2024-12-12

图片描述

老师好,
既然Button组件,要么是button 要么是a, 那么ButtonProps是不是可以设置为联合类型呢? 如下所示:

export type ButtonProps = NativeButtonProps | AnchorButtonProps
写回答

1回答

张轩

2024-12-13

同学你好

这个场景下使用联合类型确实是更好的选项,甚至你可以使用一个类型收窄的方法让组件更加完美:

function isAnchorButton(props: ButtonProps): props is AnchorButtonProps {
    return 'href' in props;
}

const Button = (props: ButtonProps) => {
    if (isAnchorButton(props)) {
        // 这里 TypeScript 能够准确推断出 props 的类型是 AnchorButtonProps
        return <a href={props.href}>{props.children}</a>
    }
    // 这里会被推断为 NativeButtonProps
    return <button type={props.type}>{props.children}</button>
}


0
1
李允鹰
非常感谢!
2024-12-14
共1条回复

React18+TS高仿AntD从零到一打造组件库

设计,开发,测试,发布再到 CI/CD,从0到1造轮子

2124 学习 · 959 问题

查看课程