How do I add attributes to existing HTML elements in TypeScript/JSX?

前端 未结 4 2170
栀梦
栀梦 2020-12-15 17:46

Anyone know how to properly add/extend all native HTML element attributes with custom ones?

With the TypeScript documentation for merging interfaces, I thought that

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 18:10

    Looks like in older versions of type definition files (v0.14) the interfaces were simply declared under a global React namespace, so previously you could use the standard merging syntax.

    declare namespace React {
    
        interface HTMLProps extends HTMLAttributes, ClassAttributes {
        }
    }
    

    However the new version of d.ts file (v15.0) have declared everything inside a module. Since modules do not support merging, to the best of my knowledge the only option right now seems to be module augmentation: https://www.typescriptlang.org/docs/handbook/declaration-merging.html

    I did the following experiment and it worked for me:

    import * as React from 'react';
    
    declare module 'react' {
         interface HTMLProps {
            block?:string;
            element?:string;
            modifiers?:string;
        }
    
    }
    
    export const Foo = () => {
    
        return (
            
    ) };

    Obviously this is quite tedious, you could put the augmentation code in another file as shown in the example from the typescript handbook, and import it:

    import * as React from 'react';
    import './react_augmented';
    

    But it's still quite dirty. So maybe it's best to address the issue with the contributors of the type definition file.

提交回复
热议问题