使用next-auth构建Next.js项目时遇TypeScript编译错误求助
Next.js构建时next-auth类型错误解决方案
问题详情
执行next build命令构建项目时触发TypeScript编译错误,具体报错信息如下:
> next build Linting and checking validity of types ..Failed to compile. ./node_modules/next-auth/src/core/errors.ts:11:11 Type error: No overload matches this call. Overload 1 of 2, '(message?: string, options?: ErrorOptions): Error', gave the following error. Argument of type 'string | Error' is not assignable to parameter of type 'string'. Type 'Error' is not assignable to type 'string'. Overload 2 of 2, '(message?: string): Error', gave the following error. Argument of type 'string | Error' is not assignable to parameter of type 'string'. Type 'Error' is not assignable to type 'string'. 9 | constructor(error: Error | string) { 10 | // Support passing error or string > 11 | super((error as Error)?.message ?? error) | ^ 12 | this.name = "UnknownError" 13 | this.code = (error as any).code 14 | if (error instanceof Error) {
当前环境版本:
- node
v18.12.1 - yarn
v1.22.19 - next.js
v13.5.2 - typescript
v4.8.4
已尝试调整TypeScript、Next.js、next-auth版本,问题仍未解决,怀疑是包版本不兼容或next-auth自身类型定义问题。
可行解决方案
1. 修复next-auth类型定义并固化补丁
错误根源是TypeScript无法推断(error as Error)?.message ?? error的类型为字符串,可通过显式类型断言解决:
- 打开
node_modules/next-auth/src/core/errors.ts,将第11行修改为:super(((error as Error)?.message ?? error) as string) - 为避免重启构建后修改失效,使用
patch-package固化补丁:- 安装依赖:
yarn add patch-package --dev - 生成补丁文件:
yarn patch-package next-auth - 将项目根目录生成的
patches/next-auth+<对应版本号>.patch文件提交到版本控制,后续安装依赖时会自动应用该补丁。
- 安装依赖:
2. 升级TypeScript版本
TypeScript 4.8.x对可选链与空值合并组合的类型推断存在局限,升级到v4.9.x及以上版本可改善类型推断能力:
yarn add typescript@^4.9.0 --dev
执行完升级后重新运行next build。
3. 锁定兼容的next-auth版本
部分旧版next-auth存在类型定义缺陷,升级到与Next.js 13.5.2兼容的版本(如next-auth@^4.23.0)可直接解决该问题:
yarn add next-auth@^4.23.0
内容的提问来源于stack exchange,提问作者Kozlo
相关产品推荐
相关产品推荐

