有人知道如何使用自定义属性正确地添加/扩展所有本机HTML元素属性吗?
有了用于合并接口的TypeScript文档,我想我可以这么做:
interface HTMLElement {
block?: BEM.Block;
element?: BEM.Element;
modifiers?: BEM.Modifiers;
}
<div block="foo" />; // error
但是,我在vscode 1.6.1 (最新)中得到以下Intellisense错误:
类型'HTMLProps‘上不存在ts属性’块‘。
他们所指的HTMLProps
是React.HTMLProps<T>
,div
元素声明如下所示:
namespace JSX {
interface IntrinsicElements {
div: React.HTMLProps<HTMLDivElement>
}
}
我试图重新声明div
,但没有结果。
相关:https://github.com/Microsoft/TypeScript/issues/11684
编辑:,这是最后为我工作的东西:
declare module 'react' {
interface HTMLAttributes<T> extends DOMAttributes<T> {
block?: string
element?: string
modifiers?: Modifiers // <-- custom interface
}
}
发布于 2019-05-13 09:50:06
最新的例子(2019年5月)
React定义文件(默认情况下是index.d.ts
,当使用create-react-app
时)包含所有标准HTML元素的列表,以及已知的属性。
为了允许自定义HTML属性,您需要定义它的类型。通过扩展HTMLAttributes
接口来做到这一点:
declare module 'react' {
interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
// extends React's HTMLAttributes
custom?: string;
}
}
https://stackoverflow.com/questions/40093655
复制相似问题