简体   繁体   English

如何在 TypeScript 中使用扩展 `koa.Request` 的包?

[英]How can I use packages that extend `koa.Request` in TypeScript?

I am trying to use koa-tree-router and koa-bodyparser at the same time, but I keep getting TypeScript errors:我试图同时使用koa-tree-routerkoa-bodyparser ,但我不断收到 TypeScript 错误:

export const userLoggingRouter = new KoaTreeRouter<any, DefaultContext>();

userLoggingRouter.post('/logs/action', (ctx) => {
  const logEntries = ctx.request.body;
  const user = ctx.state.user;

  // ...
});

error TS2339: Property 'body' does not exist on type 'Request'.错误 TS2339:类型“请求”上不存在属性“正文”。

I have @types/koa-bodyparser installed, and it contains the following definition:我安装了@types/koa-bodyparser ,它包含以下定义:

import * as Koa from 'koa';

declare module 'koa' {
    interface Request {
        body: string | Record<string, unknown>;
        rawBody: string;
    }
}

But it doesn't seem to do anything.但它似乎没有做任何事情。 I found this question , but importing koa-bodyparser directly also does not do anything.我发现了这个问题,但是直接导入koa-bodyparser也没有做任何事情。 How do I get TypeScript to recognize the extended Request type?如何让 TypeScript 识别扩展Request类型?

Edit: Creating a .d.ts file inside my project containing the following:编辑:在我的项目中创建一个包含以下内容的.d.ts文件:

import {Request} from "koa";

declare module "koa" {
  interface Request {
    body: any;
  }
}

Made the compile error go away, but this seems like an inelegant solution because I would have to copy over type information for every package that modifies koa.Request .使编译错误 go 消失,但这似乎是一个不优雅的解决方案,因为我必须为每个修改koa.Request的 package 复制类型信息。

This was happening because I was using Yarn PnP and I had two different versions of @types/koa installed.发生这种情况是因为我使用的是 Yarn PnP,并且安装了两个不同版本的@types/koa Once I added a resolutions field to my package.json that forced all of the other TypeScript definitions to use the same version of @types/koa , everything worked.一旦我向我的package.json添加了一个resolutions字段,强制所有其他 TypeScript 定义使用相同版本的@types/koa ,一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM