【发布时间】:2021-09-04 13:28:40
【问题描述】:
我正在尝试同时使用 koa-tree-router 和 koa-bodyparser,但我不断收到 TypeScript 错误:
export const userLoggingRouter = new KoaTreeRouter<any, DefaultContext>();
userLoggingRouter.post('/logs/action', (ctx) => {
const logEntries = ctx.request.body;
const user = ctx.state.user;
// ...
});
错误 TS2339:“请求”类型上不存在属性“正文”。
我安装了@types/koa-bodyparser,它包含以下定义:
import * as Koa from 'koa';
declare module 'koa' {
interface Request {
body: string | Record<string, unknown>;
rawBody: string;
}
}
但它似乎没有做任何事情。我找到了this question,但是直接导入koa-bodyparser 也没有任何作用。如何让 TypeScript 识别扩展的 Request 类型?
编辑:在我的项目中创建一个.d.ts 文件,其中包含以下内容:
import {Request} from "koa";
declare module "koa" {
interface Request {
body: any;
}
}
使编译错误消失,但这似乎是一个不优雅的解决方案,因为我必须为每个修改 koa.Request 的包复制类型信息。
【问题讨论】:
标签: node.js typescript koa