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

2022-11-28 16:01:02 +08:00
 Danswerme

今天看到张鑫旭推荐的 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 还是会提示必须是相同的类型,找了一圈没找到解决办法,大家有什么解决办法吗?

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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/898543

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX