首页 > 解决方案 > 尝试在 vue.js 中使用 clear() 清除表单时出现 Typescript 错误

问题描述

当用户单击重置按钮时尝试重置表单时出现打字稿错误。

onClearSearchFormClicked() {
  this.$refs.searchForm.reset();
}
197:27 Property 'reset' does not exist on type 'Element | Element[] | Vue | Vue[]'.
  Property 'reset' does not exist on type 'Element'.
    196 |   onClearSearchFormClicked() {
  > 197 |     this.$refs.searchForm.reset();
        |                           ^
    198 |   }
Version: typescript 3.8.3

标签: javascripttypescriptvue.js

解决方案


我不会建议其他答案。TypeScript 正确地告诉您该对象不能是 HtmlFormElement。而不是强制转换和抑制错误,您宁愿使用类型保护

if (this.$refs.searchForm instanceof HTMLFormElement) {
  this.$refs.searchForm.clear();
}

推荐阅读