首页 > 解决方案 > TypeScript + Express:“IncomingMessage”类型上不存在属性“rawBody”

问题描述

在我的src/app.ts,我有:

import express from 'express';
import bodyParser from 'body-parser';
const app = express()

app.use(bodyParser.json({ verify: (req, res, buf) => req.rawBody = buf }))

但我得到了错误Property 'rawBody' does not exist on type 'IncomingMessage'

app.use(bodyParser.json({ verify: (req, res, buf) => req.rawBody = buf }))

我有一个typings/express.d.ts,其中我有:

declare namespace Express {
    export interface Request {
        rawBody: any;
    }
}

tsconfig.json的是:

{
    "compilerOptions": {
        "outDir": "./built",
        "allowJs": true,
        "target": "es6",
        "esModuleInterop": true,
        "sourceMap": true,
        "moduleResolution": "node"
    },
    "include": [
        "./src/**/*"
    ],
    "files": [
        "typings/*"
    ]
}

那么我做错了什么?

标签: node.jstypescriptexpress

解决方案


这里有两个问题:

1.tsconfig.json

中的files选项tsconfig.json不支持通配符typings/*,仅支持显式文件名。

您可以指定完整路径:

"files": [
    "typings/express.d.ts"
]

或将通配符路径添加到include

"include": [
    "./src/**/*",
    "typings/*"
]

2.错误类型

错误消息提到了 type IncomingMessage,但是您正在扩充Request界面。看一下body-parser(部分省略)的类型定义:

import * as http from 'http';

// ...

interface Options {
    inflate?: boolean;
    limit?: number | string;
    type?: string | string[] | ((req: http.IncomingMessage) => any);
    verify?(req: http.IncomingMessage, res: http.ServerResponse, buf: Buffer, encoding: string): void;
}

的第一个参数具有 Node.js 中包含的模块verify的类型。http.IncomingMessage'http'

要增加正确的类型,您需要将.d.ts文件更改为:

declare module 'http' {
    interface IncomingMessage {
        rawBody: any;
    }
}

推荐阅读