Vue 3 + Typescript emit function "No overload matches this call" 即使定义了函数名。看起来订单很重要

Vue 3 + Typescript emit function "No overload matches this call" even if the function name is defined. It looks like order matters

当我将它与 TypeScript 一起使用时,我在 Vue 3 emit 函数中发现了一条奇怪的错误消息。 要重现的示例代码:

export default defineComponent({
  emits: {
    emit1: (payload: number) => payload,
    emit2: (payload: string) => payload
  },
  methods: {
   ...
  }
}

当我尝试像下面这样调用 emit1 时,它编译没有错误: this.$emit("emit1", 1);

但如果我执行以下操作,则会出现奇怪的错误: this.$emit("emit1", "test");

TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type '"emit1"' is not assignable to parameter of type '"emit2"'.

如果我像这样更改发射函数的顺序:

export default defineComponent({
  emits: {
    emit2: (payload: string) => payload,
    emit1: (payload: number) => payload
  },
  methods: {
   ...
  }
}

当然也会出现错误,但至少这个更有意义:

TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type 'boolean' is not assignable to parameter of type 'number'.

由于在这两种情况下都定义了函数名称,因此错误消息 #1 没有意义,但 #2 有意义。

我的问题:

使用最新的 Vue CLI 版本时,这里是 emit 命令收到的完整错误。当切换发射顺序时,它仍然显示两个错误消息,只是顺序相反:

TS2769: No overload matches this call.
  Overload 1 of 2, '(event: "emit1", payload: number): void', gave the following error.
    Argument of type '"test"' is not assignable to parameter of type 'number'.

  Overload 2 of 2, '(event: "emit2", payload: string): void', gave the following error.
    Argument of type '"emit1"' is not assignable to parameter of type '"emit2"'. 

这很清楚发生了什么,但由于您只能看到其中一条消息,因此非常混乱:

  • Vue 正在针对所有可能匹配的 emits 条目(即重载)测试发射。您在方法中使用的发射名称和发射值都作为参数提供给测试函数。这就是您看到 eventpayload 作为参数传递的地方。

  • 有一个重载,event 参数匹配,但 value 参数导致类型错误。与另一个,没有 event 匹配。