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

基于参数值从Vue 3重载函数中提取函数参数(Emits场景)

解决Vue重载Emit函数的参数提取问题

要从交集类型的emit函数中提取指定事件的参数,你需要调整类型推断逻辑,精准匹配目标事件的函数签名:

type Emits = ((event: "confirm", value: number) => void) & ((event: "cancel", test: string) => void);

// 通用工具类型:提取指定事件的参数列表
type ExtractEmitParams<EmitType, EventName extends string> = 
  EmitType extends { (event: EventName, ...args: infer Params): void } 
    ? Params 
    : never;

// 提取"confirm"事件的参数
type ConfirmAction = ExtractEmitParams<Emits, "confirm">; // 类型为 [number]

原方案返回never的原因

你的原始写法直接让Emits(两个函数的交集类型)匹配(event: 'confirm', ...args: infer T) => void,但交集类型要求同时满足所有分支的签名。由于第二个函数签名(event: "cancel", test: string) => void无法适配event: 'confirm'的约束,整个条件判断不成立,因此返回never。

而通过泛型工具类型,TypeScript会尝试将交集类型中的每个分支分别与目标签名匹配,找到符合条件的分支后提取参数,从而正确得到[number]类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:35:08