问题描述
报错信息如下所示:
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>()
...