我正在嘗試將新屬性附加到打字稿中的請求物件。這是代碼:
import { request, Request, response, Response } from "express";
((req: Request, res: Response) => {
console.log(req.user);
})(request, response)
我這樣宣告:
declare global {
namespace Express {
interface Request {
user: string;
}
}
}
然后我用 ts-node 運行它。結果是:
/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:843
return new TSError(diagnosticText, diagnosticCodes, diagnostics);
^
TSError: ? Unable to compile TypeScript:
x.ts:9:21 - error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
9 console.log(req.user);
~~~~
at createTSError (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:843:12)
at reportTSError (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:847:19)
at getOutput (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1057:36)
at Object.compile (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1411:41)
at Module.m._compile (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1596:30)
at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Object.require.extensions.<computed> [as .ts] (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1600:12)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:827:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
diagnosticCodes: [ 2339 ]
}
我測驗了太多網站的答案,但其中一個沒有奏效。請幫忙。
uj5u.com熱心網友回復:
- 首先,我認為您的宣告檔案有一些問題。像這樣編輯檔案
export {}
declare global {
namespace Express {
interface Request {
user: string;
}
}
}
或者
namespace Express {
interface Request {
user?: string
}
}
- 添加包含宣告檔案的目錄
tsconfig。由于我通常將其命名express.d.ts并放置在src/types檔案夾中,在我的情況下,tsconfig.json將像這樣編輯
{
"compilerOptions": {
"typeRoots": ["src/types"],
}
}
- 最后,還要在
tsconfig.json. (不在compilerOptions)
{
"ts-node": {
"files": true
}
}
uj5u.com熱心網友回復:
您是否正在尋找@types/express?
您也可以使用交叉點型別修復它:
function endpoint (req: Request, res: Response & {user: string;}) {
console.log(req.user);
}
但也許你正在尋找req.body.user,型別Response<{user: string;}>?
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/486074.html
