我尝试使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'
user
由express-jwt
添加到请求对象上。
我该如何解决?
答案 0 :(得分:0)
使用一个属性扩展Express Request
interface AuthRequest extends express.Request {
user?: string
}
app.use(
'/',
expressGraphql((req: AuthRequest, res, graphQLParams) => ({
schema,
rootValue,
context: {
user: req.user
}
}))
)