Vue中如何为函数参数指定defineEmits的触发值类型
Vue + TypeScript:限定emit参数为defineEmits定义的事件类型
问题场景
在Vue项目中,通过以下代码定义组件触发事件:
const emits = defineEmits(['click-button', 'toggle-menu']);
随后编写点击处理函数,接收事件名字符串参数:
const onClick = async (emitString: string | false = false) => { if (emitString) { emits(emitString); } };
此时TypeScript报错:Argument of type 'string' is not assignable to parameter of type "click-button" | "toggle-menu",需要将emitString的类型指定为defineEmits数组中值的联合类型,但直接用局部变量配合defineEmits无法实现。
解决方法
方法1:通过常量数组复用类型
先定义包含所有事件名的常量数组(用as const锁定字面量类型),再用该数组初始化defineEmits,同时提取类型:
// 定义事件名常量数组,as const确保元素为字面量类型 const EMIT_EVENTS = ['click-button', 'toggle-menu'] as const; // 用常量数组初始化defineEmits const emits = defineEmits(EMIT_EVENTS); // 提取数组元素的联合类型 type EmitType = typeof EMIT_EVENTS[number]; // 指定参数类型为EmitType | false const onClick = async (emitString: EmitType | false = false) => { if (emitString) { emits(emitString); // 类型校验通过 } };
方法2:从emits函数提取参数类型
无需额外定义常量数组,直接通过Parameters工具类型从emits函数中提取允许的事件名类型:
const emits = defineEmits(['click-button', 'toggle-menu']); // 提取emits函数的第一个参数类型(即事件名联合类型) type EmitType = Parameters<typeof emits>[0]; const onClick = async (emitString: EmitType | false = false) => { if (emitString) { emits(emitString); // 类型校验通过 } };
内容的提问来源于stack exchange,提问作者Galivan
相关产品推荐
相关产品推荐

