Home > front end >  Using NodeJS & Typescript - how to access data of an object of type Request
Using NodeJS & Typescript - how to access data of an object of type Request

Time:02-23

I need to get access to

req.kauth.grant

which is populated for sure - because printing req prints me this:

kauth: {
    grant: Grant {
      access_token: [Token],
      refresh_token: undefined,
      id_token: undefined,
      token_type: undefined,
      expires_in: undefined,
      __raw: ....
}

but if I try to directly print like this

router.get('/', keycloak.protect(), async (req:Request, res:Response):Promise<void> => {
    console.log(req.kauth);
    res.send("hello");
});

I get:

[ERROR] 18:32:14 ⨯ Unable to compile TypeScript:
src/api/routes/elev.ts:11:21 - error TS2339: Property 'kauth' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

11     console.log(req.kauth);

It's my first time using Typescript with NodeJS, so if I'm missing something obvious, I'm sorry.

So, how can I access that field in this case?

Thanks :)

CodePudding user response:

The problem here is that kauth is not a property in the Request type. That's what the error message is telling you. Therefore, you have two options. Either extend the Request type (search for ways to do that) or tell typescript to ignore the error by putting a // @ts-ignore line above the console.log line giving you the error message.

CodePudding user response:

You should tell typescript that the Request object has the kauth property:

interface kAuthRequest extends Request {
    kauth: {grant: {[key: string]: unknown}}
}

Then, instead of using type Request, you use kAuthRequest.

Or, if all Request objects will have that property, you can directly add it onto the interface:

interface Request {
    kauth: {grant: {[key: string]: unknown}}
}

See the documentation for interfaces and declaration merging for more information.

  • Related