You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中为多个Mongoose方法注册相同钩子?

解决TypeScript严格模式下Mongoose批量注册pre钩子的类型错误

在非TypeScript严格模式下,以下批量注册Mongoose pre钩子的代码可以正常运行:

const hooks = [ 'find', 'findOne', 'update' ];

UserSchema.pre( hooks, function( next ) {
    // 钩子逻辑
    next();
}

但启用严格模式后会触发类型错误:No overload matches this call,原因是TypeScript会将普通数组hooks推断为string[]类型,而Mongoose的pre方法要求传入的钩子名称必须属于其定义的HookName联合类型(包含所有合法的钩子方法名),两者类型不匹配导致报错。

修复方案

方案1:显式指定数组类型为HookName

导入Mongoose的HookName类型,为数组指定明确类型:

import type { HookName } from 'mongoose';

const hooks: HookName[] = ['find', 'findOne', 'update'];

UserSchema.pre(hooks, function(next) {
    // 钩子逻辑
    next();
});

方案2:使用as const断言锁定数组字面量类型

通过as const让TypeScript将数组推断为字面量联合类型,匹配pre方法的参数要求:

const hooks = ['find', 'findOne', 'update'] as const;

UserSchema.pre(hooks, function(next) {
    // 钩子逻辑
    next();
});

方案3:直接传入字面量数组

跳过变量定义,直接在pre方法中传入字面量数组,TypeScript会自动推断正确的联合类型:

UserSchema.pre(['find', 'findOne', 'update'], function(next) {
    // 钩子逻辑
    next();
});

以上三种方案都能让TypeScript严格模式下通过类型检查,实现批量注册相同逻辑的pre钩子。

内容的提问来源于stack exchange,提问作者Katai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 23:42:03