src/
- types/
- express/
- index.d.ts
import express from "express";
declare global {
namespace Express {
interface Request {
user?: Record<string,any>
}
}
}
{
"compilerOptions": {
"typeRoots" : ["./src/types", "./node_modules/@types"]
}
}
这应该可以运行
我之前也遇到了同样的问题,以下是我是如何解决的。
import * as express from "express"
declare global {
namespace Express {
interface Request {
user? : Record<string,any>
}
}
}
"compilerOptions": {
...other settings,
"typeRoots": ["@types", "node_modules/@types"],
...other settings
}
就这些了。在这些更改后它应该可以工作。
typeRoots
放在compilerOptions
内部。我之前是将它们放在外面的。感谢这个答案! - Gabriel Arghire["./types", "node_modules/@types"]
而不是["node_modules/@types", "./types"]
。 - Marshmellow1328import { NextFunction, Request, Response } from 'express';
interface IDecode {
address: string,
role: string,
iat: number,
exp: number
};
interface RequestWithUserRole extends Request {
user?: IDecode,
}
const parseToken = (secret: string) =>
async (req: RequestWithUserRole, res: Response, next: NextFunction) => {
try{
const token = req.headers?.authorization?.split(' ')[1];
// console.log(req.headers?.authorization);
if (!token) {
return res.status(403).json({message: 'Token not found'})
}
const decodedData = <IDecode> jwt.verify(token, secret);
req.user = decodedData;
// console.log(decodedData);
return next();
}
catch(e) {
return res.status(500).json({e})
}
};
npm install -D @types/passport
(req as any).user
。
user
对象是否需要是可选的?目前为止,如果不是可选的,我没有收到错误信息。 - tim.rohrer