Element Plus 组件 TypeScript 类型校验问题
问题描述
在使用 Element Plus 的 el-option
组件时,发现传入未定义的 prop :values
没有得到 TypeScript 的类型校验提示。
<el-option :value="item.value" :label="item.label" :values="item.value" />
<!-- 这里的 values 属性在SelectOptionProxy接口中并未定义 -->
原因分析
Vue 3 模板中的类型检查机制相对宽松
默认情况下,Vue 允许向组件传递"额外"的 props
TypeScript 主要针对
.ts/.tsx
文件进行类型检查,Vue 模板需要额外配置
解决方案
1. 开启严格模板类型检查
在 tsconfig.json
中添加:
{
"vueCompilerOptions": {
"strictTemplates": true
}
}
2. 使用 defineProps 显式声明类型
const props = defineProps<{
value: string | number;
label: string | number;
// ... 其他属性
}>();
3. 配置 ESLint
安装并配置 ESLint 的 Vue 插件:
// .eslintrc.js
module.exports = {
plugins: ["vue"],
rules: {
"vue/no-unused-properties": [
"error",
{
groups: ["props", "data", "computed", "methods"],
},
],
},
};
最佳实践
严格遵循组件的类型定义
移除未定义的属性(如本例中的
:values
)开启严格的类型检查配置
使用 IDE 插件辅助开发(如 Volar)
相关接口定义
Element Plus 的 SelectOption 接口定义:
export interface SelectOptionProxy {
value: string | number | Record<string, string>;
label: string | number;
created: boolean;
disabled: boolean;
currentLabel: string;
itemSelected: boolean;
isDisabled: boolean;
select: SelectContext;
hoverItem: () => void;
updateOption: (query: string) => void;
visible: boolean;
hover: boolean;
selectOptionClick: () => void;
}