在我的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/*"
]
}
那么我到底做错了什么呢?
发布于 2019-09-23 02:27:09
这里有两个问题:
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;
}
}
https://stackoverflow.com/questions/58049052
复制相似问题