mitt 3.0新版本帶來的問題 is not assignable to parameter of type 'Handler


問題描述

報錯信息如下所示:

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>()

    ...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM