如何在 FastifyRequest 的接口中添加属性而不覆盖声明文件中的所有内容

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

如何使用声明向接口添加属性,而不覆盖该对象中的所有内容。

declare module 'fastify' {
  interface FastifyRequest {
      user: User;
  }
}


//auth.ts

...
    const user = jwt.verify(
        req.headers.authorization ?? '', // Property 'headers' does not exist on type 'FastifyRequest'.ts(2339)
...
typescript declaration
1个回答
0
投票

我找到了解决方案:

只需使用您声明的模块添加导入或添加三斜杠引用,例如:

/// <reference path="<path-to-typings-dir>" />
or
import fastify from "fastify";

declare module 'fastify' {
    export interface FastifyRequest {
        user: any;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.