You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何覆盖ButtonHTMLAttributes.type枚举?解决uni-app按钮TS报错

解决uni-app Button组件TypeScript类型报错问题

问题背景

uni-app的button组件type属性支持"default" | "primary" | "warn",但Vue原生ButtonHTMLAttributes的type仅允许"button" | "submit" | "reset" | undefined,导致VSCode中设置type="primary"时出现TS类型错误:

Type '"primary"' is not assignable to type '"submit" | "reset" | "button" | undefined'.ts-plugin(2322)

有效解决方案

1. 正确扩展Vue类型声明(推荐)

如果之前添加uni.d.ts未生效,大概率是写法或配置问题,按以下步骤操作:

  • 在项目根目录或src目录下创建/修改uni.d.ts文件,写入以下代码:
import type { ButtonHTMLAttributes } from 'vue';

declare module 'vue' {
  interface ButtonHTMLAttributes {
    // 合并uni-app支持的类型与原生类型
    type?: 'default' | 'primary' | 'warn' | 'button' | 'submit' | 'reset';
  }
}

// 针对DOM元素的补充声明(可选,增强兼容性)
declare module '@vue/runtime-dom' {
  interface HTMLButtonElement {
    type?: 'default' | 'primary' | 'warn' | 'button' | 'submit' | 'reset';
  }
}

export {};
  • 确保tsconfig.json的include字段包含该文件:
{
  "include": ["src/**/*", "uni.d.ts"]
}

修改后重启VSCode,类型检查即可生效。

2. 临时绕过类型检查(快速解决)

如果不想修改全局类型,可通过以下方式临时屏蔽报错:

  • 使用// @ts-ignore注释跳过当前行检查:
<!-- @ts-ignore -->
<button type="primary">提交</button>
  • 使用类型断言强制转换:
<button :type="('primary' as unknown) as 'button'">提交</button>

3. 引入uni-app官方类型声明

确保已安装并配置uni-app官方TS类型:

  • 安装依赖:
npm install @dcloudio/types --save-dev
  • 在tsconfig.json中添加类型引用:
{
  "compilerOptions": {
    "types": ["@dcloudio/types"]
  }
}

内容的提问来源于stack exchange,提问作者DengSihan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 10:52:35