使用foo作为属性会引发错误:

// App.tsx
//                     ? throws
const App = () => <div foo></div>

export default App
Type '{ foo: true; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.
  Property 'foo' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.ts(2322)

但是使用foo-foo是可以的,为什么?

// App.tsx
//                     ? no error is thrown
const App = () => <div foo-foo></div>

export default App

And most importantly, how to define types like this in TypeScript? i.e. Only allowing standard or kebab-case attributes.

推荐答案

答案就在JSX section of the Typescript Handbook个选项中:

如果属性名称不是有效的JS identifier(如data-*属性),则如果在元素属性类型中找不到该名称,则不认为该名称是错误.

关于JSX的整个章节都非常有启发性.

"如何在TypeScript中定义这样的类型"问题的答案恐怕是...我们没有.JSX支持内置于编译器中.不过,我们可以定制很多有趣的东西.

Vue.js相关问答推荐

Vuetify快速失败不会阻止发送表单

使用项目和字段,列跨度为 2 的 Bootstrap-vue 表

点击屏幕的任何位置都会禁用v-overlay

在 VueJS 中存储图像的正确位置是什么 - 公共文件夹或assets文件夹?

用 axios 搜索:新字符时取消之前的请求

Vuelidate 判断true/false

在组件上的 Vue 3 中获取 URL 查询参数

VueJS:向左,元素的顶部位置?

使用 vee-validate 在 vue js 中进行验证有错误

在基于 TypeScript 的 Vue 中将 vuex 状态和Mutations绑定到复选框组件属性

使用 Vee-Validate 在提交时验证子输入组件

如何克隆props对象并使其无react

为什么 v-model 不适用于数组和 v-for 循环?

如何避免在 Vue 中一直写 this.$store.state.donkey 的需要?

如何将 Angular 和 Vue 项目合并在一起?

将登录页面包含在单页应用程序中是否不安全?

使用 axios 和 vue.js 取消先前的请求

mount() 仅在组件 Vue.js 上运行一次

Vuetify 离线文档

v-bind:class 的 Vue.js 计算(computed)属性