mitt 3.0新版本帶來的問題 is not assignable to parameter of type 'Handler<unknown>
阿新 • • 發佈:2021-10-02
問題描述
報錯資訊如下所示:
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 = [] })
修改後的程式碼
GitHub : https://github.com/fxiaoyu97import 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 } type Emitter = Emits<'form-item-created', ValidateFunc> export const emitter: Emitter = mitt<Emitter>() ...
部落格園 : https://www.cnblogs.com/tudou1179006580
微信公眾號 : 三更程式設計菌
Copyright ©2019 卡洛小豆
【轉載文章務必保留出處和署名,謝謝!】