본문 바로가기

error records

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

반응형

Typescript 

import { Request, Response } from 'express';

const exec = async (req: Request, res: Response, next: Function): Promise<void> => {
  const { idx } = req.user;
  const { restaurantIdx } = req.params;

.
.
.

};

export default { exec };

 

빨간 줄이 간 .user  

You can see the res line above, the error is : 

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

 

기본적으로 express에서 가져온 Request에는 user라는 프로퍼티가 없다. 해당 프로퍼티와 그 타입을 지정한 인터페이스를 가져와서 타입으로 지정해주면 된다! 

 

Basically the Type I am using for "req"  is Request type from 'express', but is doesn't have User type which is pesonally made. Therefore you can just make a new "User" added Interface type that is extended from 'express.Request' like below.

 

import { Request, Response } from 'express';
import User from '../User.interface'

export interface IUserAddedRequest extends Request {
  user: User;  // User is already an Interface
}

const exec = async (req: IUserAddedRequest, res: Response, next: Function): Promise<void> => {
  const { idx } = req.user; // now there is no red line
  const { restaurantIdx } = req.params;

.
.
.

};

export default { exec };

 

빨간 줄이 사라지고 에러가 해결되었다. 

And now it works ! 

 

 

 

reference : https://stackoverflow.com/questions/44383387/typescript-error-property-user-does-not-exist-on-type-request

반응형