如何使用TypeScript扩展Fastify中的Request接口

c9qzyr3d  于 2023-02-05  发布在  TypeScript
关注(0)|答案(2)|浏览(238)

我在项目的根目录下有一个名为fastify.d.ts的声明文件:

import { auth } from "firebase-admin";

declare module 'fastify' {
  interface FastifyRequest {
    user: auth.DecodedIdToken
  }
}

我一直在使用将user设置为传入请求,例如:

export default async function mustBeLoggedIn(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    const token = req.headers.authorization?.replace("Bearer ", "") ?? "";

    const result = await auth.verifyIdToken(token);

    req.user = result;
  } catch (err) {
    reply.status(401).send({
      error: "You must be logged in to access this resource",
    });
  }
}

我得到了错误:middlewares/mustBeLoggedIn.ts(13,9): error TS2339: Property 'user' does not exist on type 'FastifyRequest<RouteGenericInterface, Server, IncomingMessage>'.
当前tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
  },
  "include": ["**/*.ts", "**/*.d.ts"],
  "exclude": ["node_modules"]
}

我该怎么办?谢谢!

k4aesqcs

k4aesqcs1#

"ts-node": {  "files": true },

tsconfig.json的根级别。
https://stackoverflow.com/a/68488480/6398044

bvjveswy

bvjveswy2#

尝试导入FastifyRequest,如下所示:

import FastifyRequest from "fastify";
import { auth } from "firebase-admin";

declare module 'fastify' {
  interface FastifyRequest {
    user: auth.DecodedIdToken
  }
}

相关问题