在我的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/*"
    ]
}

那我在做什么错?

最佳答案

这里有两个问题:

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

您可以指定完整路径:

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

或将通配符路径添加到include:
"include": [
    "./src/**/*",
    "typings/*"
]

2.错误的类型

该错误消息提到类型IncomingMessage,但是您正在增加Request接口(interface)。看一看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;
}
verify的第一个参数的类型为Node.js附带的http.IncomingMessage模块中的'http'

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

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

09-04 14:50