【发布时间】:2020-08-12 10:58:13
【问题描述】:
有没有办法为 react HTML 元素添加自定义类型?我将 React 16.13.1 与 Create React App 和 Typescript 3.9.5 一起使用。我找到的唯一解决方案是禁用类型检查,这并不理想,或者在每个组件的顶部声明 react 模块接口(如下所示)。有没有办法在全球范围内添加它?还是其他解决方案?
declare module 'react' {
interface HTMLAttributes<T> {
customAttribute?: any;
// more attributes...
}
}
我尝试将它添加到创建的 index.d.ts 文件并添加到 tsconfig.json "compilerOptions": {"types":["./index.d.ts"]} 但我仍然得到
TS2322: Type '{ children: Element[]; customAttribute: string; className: string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'. Property 'customAttribute' does not exist on type
感谢您的帮助。
【问题讨论】:
-
您是否尝试使用声明文件?在你的项目中添加一个
index.d.ts,类型应该是全局可用的 -
是的。当我说我创建了一个
index.d.ts文件但我仍然收到 TS2322 错误时,这就是我正在尝试的。 -
查看了有关声明的文档后,我意识到我错误地导出和导入了我的声明。感谢您的评论,确认声明是正确的前进方式。
标签: reactjs typescript