Javascript 尝试编译TypeScript-失败:如果(!req.session?.jwt){…}
以代码为例:Javascript 尝试编译TypeScript-失败:如果(!req.session?.jwt){…},javascript,typescript,compilation,Javascript,Typescript,Compilation,以代码为例: import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; export const currentUser = ( req: Request, res: Response, next: NextFunction ) => { if (!req.session?.jwt) { // make sure that session
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
export const currentUser = (
req: Request,
res: Response,
next: NextFunction
) => {
if (!req.session?.jwt) {
// make sure that session is defind and then access "jwt" property
return next();
}
try {
const payload = jwt.verify(
req.session.jwt,
process.env.JWT_KEY!
) as UserPayload;
req.currentUser = payload;
} catch (error) {}
next();
};
对于package.json:
{
"name": "@something/common",
"version": "1.0.2",
"description": "",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"files": [
"build/**/*"
],
"scripts": {
"clean": "del build /Q",
"build": "npm run clean && tsc",
"pub": "npm version patch && npm run build && npm publish"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"del-cli": "^3.0.0",
"typescript": "^3.8.3"
},
"dependencies": {
"@types/cookie-session": "^2.0.39",
"@types/express": "^4.17.5",
"@types/jsonwebtoken": "^8.3.9",
"cookie-session": "^1.4.0",
"express": "^4.17.1",
"express-validator": "^6.4.0",
"jsonwebtoken": "^8.5.1"
}
}
每当我尝试使用tsc
编译时,我都会得到:
src/middlewares/current-user.ts:24:20 - error TS1109: Expression expected.
24 if (!req.session?.jwt) {
~
src/middlewares/current-user.ts:24:24 - error TS1005: ':' expected.
24 if (!req.session?.jwt) {
~
Found 2 errors.
什么原因可能导致这种情况?请确保
tsc
版本足够新,?
是最近添加的。这个错误是我对一个还不支持它的版本所期望的(它假设这是一个三元运算符:条件?a:b
)
也许您使用的是全局安装的版本,而不是软件包的版本