Danswerme
V2EX  ›  问与答

请教下各位 V 友, TypeScript 如何扩展 React 的 ButtonHTMLAttributes 接口里面的 type 类型?

By Danswerme at 2022 年 11 月 28 日 · 1133 次点击

今天看到张鑫旭推荐的 Lulu ui 库,想试着用一下。这个 UI 库的 button 元素可以通过设置 type 来调节不同的样式。

<button type="primary" class="ui-button">主按钮</button>

但是这样使用的话 ts 会报错,因为原生的 button type 属性是 'submit' | 'reset' | 'button' | undefined ,其中并没有 primary 这个类型。

我试着这样扩展 ButtonHTMLAttributes 这个接口:

declare module 'react' {
    interface ButtonHTMLAttributes<T> extends HTMLAttributes<T> {
        type?: 'submit' | 'reset' | 'button' | 'primary' | undefined;
    }
}

ts 还是会提示必须是相同的类型,找了一圈没找到解决办法,大家有什么解决办法吗?

2 条回复  •  2022-11-28 16:53:00 +08:00
noe132
   1
noe132  
   2022 年 11 月 28 日
declaration merging 必须得是一样的类型。react.d.ts 设计出来就没有为这样的用法做考虑。
举个其他的例子,如 @mui/material 在设计中 Button 的 color props 类型就设计成了可扩展的类型,
color?: OverridableStringUnion<
'inherit' | 'primary' | 'secondary' | 'success' | 'error' | 'info' | 'warning',
ButtonPropsColorOverrides
>;
只需要扩展 ButtonPropsColorOverrides 这个 interface 就能添加新的值
Danswerme
   2
Danswerme  
OP
   2022 年 11 月 28 日
@noe132 谢谢,material 的 Button 组件的源码我也看了,只不过它的 Button 组件是封装过的,而且也能扩展相应的接口。 而我用的这个 UI 库它直接使用了原生 HTML 元素,想扩展接口也就只能对 react.d.ts 动手脚了;不过既然不支持进行扩展那就没办法了,不过这个库好像也可以用 data-type 的用法来替代原生属性,这样就不受限制了,我再试试看吧。
© 2026 V2EX · 21ms · 3.9.8.5