mitt 3.0新版本带来的问题 is not assignable to parameter of type 'Handler<unknown>
  TEZNKK3IfmPf 2024年04月19日 21 0

报错信息如下所示:

TS2769: No overload matches this call.
  Overload 1 of 2, '(type: "*", handler: WildcardHandler<Record<EventType, unknown>>): void', gave the following error.
    Argument of type '"form-item-created"' is not assignable to parameter of type '"*"'.
  Overload 2 of 2, '(type: "form-item-created", handler?: Handler<unknown> | undefined): void', gave the following error.
    Argument of type '(func: ValidateFunc) => void' is not assignable to parameter of type 'Handler<unknown>'.
    47 |     onUnmounted(() => {
    48 |       // 删除监听
  > 49 |       emitter.off('form-item-created', callback)
       |       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    50 |       funcArr = []
    51 |     })
    52 |

原因

mitt 的定义文件有所升级

解决

修改前的代码

import mitt from 'mitt'

type ValidateFunc = () => boolean
export const emitter = mitt()

emitter.emit('formItemCreated', validateInput)

  // 将监听得到的验证函数都存到一个数组中
  const callback = (func: ValidateFunc) => {
    funcArr.push(func)
  }
  // 添加监听
  emitter.on('formItemCreated', callback)
  onUnmounted(() => {
    // 删除监听
    emitter.off('formItemCreated', callback)
    funcArr = []
  })

修改后的代码

import mitt from 'mitt'

type ValidateFunc = () => boolean

export const emitter = mitt<{
  formItemCreated: ValidateFunc
}>()
    ...

或者使用以下代码

import mitt from 'mitt'

type ValidateFunc = () => boolean

type Emits<EventType extends string | symbol, T> = {
  on(type: EventType, handler: (arg: T) => void): void
  off(type: EventType, handler: (arg: T) => void): void
  emit(type: EventType, arg: T): void
}

// 存在多个定义变量时,& 符号连接Emits
// type Emitter = Emits<'a', number> & Emits<'b', string>;
type Emitter = Emits<'form-item-created', ValidateFunc>

export const emitter: Emitter = mitt<Emitter>()

    ...
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年04月19日 0

暂无评论

TEZNKK3IfmPf