【问题标题】:TypeScript + Express: Property 'rawBody' does not exist on type 'IncomingMessage'TypeScript + Express:“IncomingMessage”类型上不存在属性“rawBody”
【发布时间】:2020-01-22 17:36:13
【问题描述】:

在我的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' on:

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.js typescript express


    【解决方案1】:

    这里有两个问题:

    1。 tsconfig.json

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

    您可以指定完整路径:

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

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

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

    2。类型错误

    错误消息提到了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;
    }
    

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

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

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

    【讨论】:

    • 当我在下游使用 req 时,它将是一个 Express 请求。所以真的,我想增强两者,不是吗?
    • @Shamoon 我想是的,是的。
    猜你喜欢
    • 2021-06-27
    • 2023-04-02
    • 2018-08-17
    • 1970-01-01
    • 2023-02-06
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    相关资源
    最近更新 更多