TypeScript + Express:“IncomingMessage”类型上不存在“rawBody”属性

Sha*_*oon 7 node.js express typescript

在我的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 }))
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误Property 'rawBody' does not exist on type 'IncomingMessage'

app.use(bodyParser.json({ verify: (req, res, buf) => req.rawBody = buf }))
Run Code Online (Sandbox Code Playgroud)

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

declare namespace Express {
    export interface Request {
        rawBody: any;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的tsconfig.json是:

{
    "compilerOptions": {
        "outDir": "./built",
        "allowJs": true,
        "target": "es6",
        "esModuleInterop": true,
        "sourceMap": true,
        "moduleResolution": "node"
    },
    "include": [
        "./src/**/*"
    ],
    "files": [
        "typings/*"
    ]
}
Run Code Online (Sandbox Code Playgroud)

那么我做错了什么?

luk*_*ter 6

这里有两个问题:

1. tsconfig.json

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

您可以指定完整路径:

"files": [
    "typings/express.d.ts"
]
Run Code Online (Sandbox Code Playgroud)

或者将通配符路径添加到include

"include": [
    "./src/**/*",
    "typings/*"
]
Run Code Online (Sandbox Code Playgroud)

2. 错误类型

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

"files": [
    "typings/express.d.ts"
]
Run Code Online (Sandbox Code Playgroud)

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

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

"include": [
    "./src/**/*",
    "typings/*"
]
Run Code Online (Sandbox Code Playgroud)