如何向 TypeScript/JSX 中的现有 HTML 元素添加属性?
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;
}
}
带有 TSX 的 Vue 3
// src/index.d.ts
import * as vue from 'vue';
declare module 'vue' {
interface HTMLAttributes {
className?: string;
vHtml?: string;
frameBorder?: string;
}
}
从 React TypeScript Cheatsheet 添加非标准属性
// react-unstable-attributes.d.ts
import"react";
declare module"react" {
interface ImgHTMLAttributes< T > extends HTMLAttributes< T > {
loading?:"auto" |"eager" |"lazy";
}
}
对于 vue,以下工作:
declare module 'vue-tsx-support/types/dom' {
interface InputHTMLAttributes {
autocorrect: string;
autocapitalize
}
}