Project structure:
☁ extends-react-types tree -I 'node_modules'
.
├── App.tsx
├── index.d.ts
├── package-lock.json
├── package.json
└── tsconfig.json
0 directories, 5 files
package version:
{
"name": "extends-react-types",
"devDependencies": {
"@types/react": "^16.9.56",
"typescript": "^4.3.5"
},
"dependencies": {
"react": "^16.8.6"
}
}
tsconfig.json
:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom"
],
"allowSyntheticDefaultImports": true,
"moduleResolution": "Node",
"jsx": "preserve",
}
}
App.tsx
:
import React from 'react';
interface HomeProps extends React.ComponentPropsWithRef<'div'> {}
export default function Home(props: HomeProps) {
return (
<div>
<p _name="name" _error={true}>
123
</p>
</div>
);
}
As you can see, there are two custom HTML attributes in p
element: _name
and _error
. Now, we need to extend HTMLAttributes
interface of React
with these two custom HTML attributes.
Option 1:
index.d.ts
:
import 'react';
declare module 'react' {
interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
_name?: string;
_error?: boolean;
}
}
Output:

Option 2:
declare namespace React {
interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
_name?: string;
_error?: boolean;
}
}
Output:
