typescript 属性'X'在类型'FastifyContext '上不存在< unknown>

oalqel3c  于 2023-10-22  发布在  TypeScript
关注(0)|答案(1)|浏览(140)

我想将token: string字段添加到FastifyContext接口。为此,我创建了以下文件结构:

projectDir
|__src
|  |__@types
|  |  |__fastify
|  |  |  |__index.d.ts
|  |__api
|  |  |__authHook.ts
|__tsconfig.json

src/@types/fatify/index.d.ts的内容:

declare module 'fastify' {
    export interface FastifyContext<ContextConfig>{
        token: string
    }
}

src/api/authHook.ts的含量

import {FastifyRequest, FastifyReply} from "fastify";

export default async function authHook(request: FastifyRequest, reply: FastifyReply): Promise<void>{
    // Some logic 
    const token = "example_token" // some result from logic 
    request.context.token = token;
}

tsconfig.json的内容:

{
  "compilerOptions": {
     ...
     "typeRoots": ["src/@types"],
     ...
  }
}

但是当我运行代码时,我得到以下错误:

Property 'token' does not exist on type 'FastifyContext<unknown>'.

我做错了什么?

f5emj3cl

f5emj3cl1#

import { onRequestHookHandler } from "fastify";

declare module "fastify" {
  export interface FastifyRequestContext {
    token: string;
  }
}

const authHook: onRequestHookHandler = async function (request, reply) {
  const token = "example_token";
  request.context.token = token;
};

export default authHook;

相关问题