You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript:扩展接口时如何用类型别名优化函数hover描述?

解决方案

核心思路是把原生HTML按钮属性抽成独立类型别名,用交叉类型替代继承,让TypeScript在类型提示时保留别名,而非展开所有属性。

修改后的代码如下:

// 单独抽离原生按钮属性为类型别名
type HtmlButtonProps = Omit<React.ComponentPropsWithRef<"button">, "children">;

// 自定义基础属性,不继承原生属性
interface ButtonCustomProps {
    block?: boolean;
    label?: string;
    icon?: IconOptions | JSX.Element;
    iconDisposition?: "none" | "left" | "right" | "icon-only";
}

type Intention = "primary" | "secondary" | "danger";

// 各变体用交叉类型组合自定义属性 + 原生属性
interface ButtonContained extends ButtonCustomProps, HtmlButtonProps {
    variant?: "contained";
    intention?: Intention;
}

interface ButtonOutlined extends ButtonCustomProps, HtmlButtonProps {
    variant: "outlined";
    intention?: Intention;
}

interface ButtonInvisible extends ButtonCustomProps, HtmlButtonProps {
    variant: "invisible";
    intention?: Extract<Intention, "primary">;
}

type ButtonProps = ButtonContained | ButtonOutlined | ButtonInvisible;

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>((props, ref) => {
    // 组件逻辑示例
    return <button ref={ref} {...props}>{props.label}</button>;
});

如果想进一步简化结构,还可以用判别式联合类型整合变体逻辑,同时保持类型提示的简洁性:

type HtmlButtonProps = Omit<React.ComponentPropsWithRef<"button">, "children">;

interface ButtonCustomBase {
    block?: boolean;
    label?: string;
    icon?: IconOptions | JSX.Element;
    iconDisposition?: "none" | "left" | "right" | "icon-only";
}

type Intention = "primary" | "secondary" | "danger";

// 用联合类型直接定义所有变体,交叉原生属性
type ButtonProps = HtmlButtonProps & ButtonCustomBase & (
    | { variant?: "contained"; intention?: Intention }
    | { variant: "outlined"; intention?: Intention }
    | { variant: "invisible"; intention?: Extract<Intention, "primary"> }
);

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>((props, ref) => {
    // 组件逻辑示例
    return <button ref={ref} {...props}>{props.label}</button>;
});

效果说明

修改后,鼠标悬浮查看Button组件的类型时,原生HTML属性会被收拢在HtmlButtonProps别名下,自定义属性和变体属性直接展示,最终提示会类似:
React.ForwardRefExoticComponent<ButtonCustomProps & HtmlButtonProps & { variant?: "contained"; ... } & React.RefAttributes<HTMLButtonElement>>
大幅提升了类型提示的可读性。

内容的提问来源于stack exchange,提问作者alexis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:01:16