使用Quasar Notify时触发TypeScript ESLint禁止Function类型报错如何解决
报错原因
你触发了@typescript-eslint/ban-types规则,该规则禁止使用顶层Function作为类型,避免失去类型校验能力带来的运行时风险。
解决方案
直接给masquerNotification声明符合实际场景的精确函数类型即可,步骤如下:
- 把原来的
Function类型替换为() => void,同时因为变量初始未赋值,要联合undefined类型兼容初始状态 - 调用
masquerNotification时使用可选链操作符,避免变量未初始化时调用抛出运行时错误
修改后的完整代码
// 替换原来的Function类型声明 let masquerNotification: (() => void) | undefined function afficherNotification () { if (notification.value && notification.value.message !== '') { masquerNotification = $q.notify({ type: notification.value.type, message: notification.value.message, position: 'bottom-right', timeout: notification.value.timeout, actions: [{ icon: 'close', color: 'white' }] }) void nettoyerNotification() } if (notification.value.masquer) { // 用可选链调用,避免undefined调用报错 masquerNotification?.() } }
补充说明
() => void显式声明了该变量是一个无入参、无返回值的函数,完全匹配Quasar Notify调用后返回的关闭函数的类型,既符合ESLint规则要求,也保留了完整的类型校验能力。
内容的提问来源于stack exchange,提问作者franfrLor
相关产品推荐
相关产品推荐

