【问题标题】:Trying to compile TypeScript - Fails : if (!req.session?.jwt) { ... }尝试编译 TypeScript - 失败:if (!req.session?.jwt) { ... }
【发布时间】:2020-06-23 12:06:22
【问题描述】:

考虑代码:

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.

这可能是什么原因?

【问题讨论】:

    标签: javascript typescript compilation


    【解决方案1】:

    确保tsc 版本足够新,.? 是最近添加的。这个错误是我对尚不支持它的版本所期望的(它假设这是一个三元运算符:condition ? a : b)。

    也许您使用的是全局安装的版本而不是软件包中的那个?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      相关资源
      最近更新 更多