类型“FastifyContext<unknown>”上不存在属性“X”

问题描述 投票:0回答:1

我想将

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>'.

我做错了什么?

typescript namespaces fastify
1个回答
0
投票

request.context
已弃用

import { onRequestHookHandler } from "fastify";

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

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

export default authHook;
© www.soinside.com 2019 - 2024. All rights reserved.