使用TypeScript导入@fastify/oauth2遇类型错误求助
解决@fastify/oauth2在TypeScript项目中注册时的TS类型错误
在TypeScript项目中导入并注册@fastify/oauth2插件时遇到TS类型不匹配错误,以下是相关配置和问题详情:
当前依赖配置
"devDependencies": { "@types/node": "^18.15.5", "@types/qs": "^6.9.7", "nodemon": "^2.0.21", "pino-pretty": "^9.4.0", "rimraf": "^4.4.1", "ts-node": "^10.9.1", "tsc-alias": "^1.8.4", "typescript": "^4.9.5" }, "dependencies": { "@fastify/cors": "^8.2.0", "@fastify/oauth2": "^7.0.1", "@trpc/client": "^10.18.0", "@trpc/server": "^10.18.0", "@types/luxon": "^3.2.0", "axios": "^1.3.4", "dotenv": "^16.0.3", "fastify": "^4.15.0", "luxon": "^3.3.0", "mysql2": "^3.2.0", "zod": "^3.21.4" }
tsconfig.json配置
{ "compilerOptions": { "baseUrl": ".", "target": "es2016", "module": "commonjs", "composite": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "outDir": "lib", "paths": { "@/*": ["src/*"] } }, "include": ["src/**/*"] }
插件注册代码
server.register(fastifyOauth2, { name: 'facebookOAuth2', credentials: { client: { id: process.env.FACEBOOK_APP_ID, secret: process.env.FACEBOOK_APP_SECRET }, auth: fastifyOauth2.FACEBOOK_CONFIGURATION }, // 注册用于启动重定向流程的fastify路由 startRedirectPath: '/login/facebook', // 用户登录后Facebook重定向到该地址 callbackUri: 'http://localhost:1337/login/facebook/callback' });
TypeScript错误信息
TS2769: No overload matches this call. Overload 2 of 3, '(plugin: FastifyPluginAsync<FastifyOAuth2Options, RawServerDefault, FastifyTypeProviderDefault, FastifyBaseLogger>, opts?: FastifyRegisterOptions<...> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error. Argument of type 'FastifyOauth2' is not assignable to parameter of type 'FastifyPluginAsync<FastifyOAuth2Options, RawServerDefault, FastifyTypeProviderDefault, FastifyBaseLogger>'
已尝试的导入方式
import fastifyOauth2 from '@fastify/oauth2'; import { fastifyOauth2 } from '@fastify/oauth2'; import * as fastifyOauth2 from '@fastify/oauth2';
三种导入方式均能解析,但都会触发上述相同错误。
问题原因及解决方案
这个问题并非使用方式错误,而是@fastify/oauth2 v7.x版本与Fastify v4.x的类型定义存在兼容性问题。以下是两种可行解决方法:
降级@fastify/oauth2版本
将依赖中的@fastify/oauth2版本降级到^6.1.0,该版本类型定义与Fastify v4.x完全兼容,降级后重新安装依赖,类型错误会自动消失。类型断言绕过检查
若不想降级版本,可通过类型断言强制告知TypeScript插件类型符合要求:import fastifyOauth2 from '@fastify/oauth2'; server.register(fastifyOauth2 as any, { // 配置项保持不变 });或使用更精确的断言:
import type { FastifyPluginAsync } from 'fastify'; import fastifyOauth2 from '@fastify/oauth2'; server.register(fastifyOauth2 as FastifyPluginAsync, { // 配置项保持不变 });
内容的提问来源于stack exchange,提问作者Vincent Brouwer
相关产品推荐
相关产品推荐

