V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Danswerme
V2EX  ›  问与答

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

  •  
  •   Danswerme · 2022-11-28 16:01:02 +08:00 · 440 次点击
    这是一个创建于 513 天前的主题,其中的信息可能已经有所发展或是发生改变。

    今天看到张鑫旭推荐的 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 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
        2
    Danswerme  
    OP
       2022-11-28 16:53:00 +08:00
    @noe132 谢谢,material 的 Button 组件的源码我也看了,只不过它的 Button 组件是封装过的,而且也能扩展相应的接口。 而我用的这个 UI 库它直接使用了原生 HTML 元素,想扩展接口也就只能对 react.d.ts 动手脚了;不过既然不支持进行扩展那就没办法了,不过这个库好像也可以用 data-type 的用法来替代原生属性,这样就不受限制了,我再试试看吧。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5953 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 02:06 · PVG 10:06 · LAX 19:06 · JFK 22:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.