Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Error: Property 'user' does not exist on type 'Request'

I have the following piece of code in my express app

router.get('/auth/userInfo', this.validateUser,  (req, res) => {     res.json(req.user); }); 

and my IDE seems to be complaining with the error

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

When I compile my typescript code it seems to be throwing this error. Any ideas why this is happening?

like image 399
RRP Avatar asked Jun 06 '17 07:06

RRP


People also ask

How do you ignore property does not exist on type?

Use a type assertion to ignore the 'Property does not exist on type' error in TypeScript, e.g. (obj as any). myProperty . Casting the object to any disables type checking and allows us to access any property on the object without getting any errors.

Does not exist on type TypeScript?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.

Does not exist on type record string any undefined?

The "Property does not exist on type String" error occurs when we try to access a property that does not exist on the string type. To solve the error, use an object instead of a string, or make sure you're accessing a valid built-in method on the string.


2 Answers

We have a large API written in Express and Typescript, and this is how we handle such scenarios:

We keep the request definitions in one file:

import { Request } from "express" export interface IGetUserAuthInfoRequest extends Request {   user: string // or any other type } 

And then in the file where we are writing the controller functions:

import { Response } from "express" import { IGetUserAuthInfoRequest } from "./definitionfile"  app.get('/auth/userInfo', validateUser,  (req: IGetUserAuthInfoRequest, res: Response) => {   res.status(200).json(req.user); // Start calling status function to be compliant with Express 5.0 }); 

Be advised that "user" is not a property that is available natively in the Request object of Express. Make sure that you are using a middleware that adds such property to the request object.

like image 199
Akshar Patel Avatar answered Oct 05 '22 01:10

Akshar Patel


req is probably of type Request from "express" package and user does not exist there. You have to either extend Request with own router handler or cast it to type any or object.

try res.json(req['user']) or res.json( (<any>req).user )

You may also use module/global augmentation

import { Request } from "express"  declare module "express" {    export interface Request {     user: any   } } 

You can also make your own handler wrapper (instead of extending Router functionality in ExpressJs).

import * as express from 'express';  interface IUserRequest extends express.Request {     user: any }  function myHandler(handler: (req: IUserRequest, res: express.Response, next?: express.NextFunction) => any) {     return (req: express.Request, res: express.Response, next: express.NextFunction) => {         try {                                          validateUser(req, res, (err) => { // your validateUser handler that makes a user property in express Request                 if(err)                      throw err;                  let requestWrapper: IUserRequest = <IUserRequest>req;                  handler(requestWrapper, res, next);             })                         }         catch (ex) {             next(ex);         }     }  }  let app = express(); // init stuff for express but this.validateUser handler is not needed  app.use('/testuser', myHandler((req, res) => {     res.json(req.user); })); 

UPDATED: Since Typescript is evolving I would also consider using Type Guards

if (hasUser(req)) {     console.log(req.user) }  function hasUser(request: Request): request is Request & { user: number } {     return 'user' in request && typeof request['user'] == 'number' } 
like image 22
Lostfields Avatar answered Oct 05 '22 00:10

Lostfields