在我的 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 }))
但我收到错误“IncomingMessage”类型上不存在属性“rawBody”
:
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.json
tsconfig.json 中的 files
选项不支持 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
的第一个参数的类型为 http.IncomingMessage
,来自 Node.js 附带的 'http'
模块。
要增强正确的类型,您需要将 .d.ts
文件更改为:
declare module 'http' {
interface IncomingMessage {
rawBody: any;
}
}
关于node.js - typescript + Express : Property 'rawBody' does not exist on type 'IncomingMessage' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58049052/