express-jwt和express-graphql:错误TS2339:类型“ Request”上不存在属性“ user”

时间:2019-01-31 14:00:02

标签: typescript express-jwt express-graphql

我尝试使express-jwt和graphql在打字稿中一起工作。

import * as express from 'express'
import * as expressGraphql from 'express-graphql'
import * as expressJwt from 'express-jwt'

import schema from './api/schemas'
import rootValue from './api/resolvers'

const app = express()

app.use(
  expressJwt({
    credentialsRequired: false,
    secret: process.env.JWT_SECRET
  })
)

app.use(
  '/',
  expressGraphql((req, res, graphQLParams) => ({
    schema,
    rootValue,
    context: {
      user: req.user
    }
  }))
)

我导入了相对类型@types/express@types/express-graphql@types/express-jwt

有一个打字稿错误:

error TS2339: Property 'user' does not exist on type 'Request'

userexpress-jwt添加到请求对象上。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

使用一个属性扩展Express Request

interface AuthRequest extends express.Request {
  user?: string
}

app.use(
  '/',
  expressGraphql((req: AuthRequest, res, graphQLParams) => ({
    schema,
    rootValue,
    context: {
      user: req.user
    }
  }))
)