프로젝트 개발 기록/[개발] trouble shooting
[Error: TS(2339)] Express Request 확장하기
HelloJudy
2022. 6. 9. 16:53
😥 문제 상황
1. Token 검증 Middleware 작성
- 토큰 검증 코드를 작성하면서 req.currentUserId로 decoded한 값을 할당하려던 중 js 프로젝트에서는 오류가 없었던 코드가 ts에서 오류가 생겼다.
// ./src/middlewares/loginRequired.ts
...
try {
if (!process.env.JWT_SECRET_KEY) {
throw new Error("JWT_SECRET_KEY가 존재하지 않습니다.");
}
const secretKey: string = process.env.JWT_SECRET_KEY;
const jwtDecoded: any = jwt.verify(userToken, secretKey);
const userId = jwtDecoded.user_id;
req.currentUserId = userId;
next();
} catch (error) {
res.status(400).send("정상적인 토큰이 아닙니다. 다시 한 번 확인해 주세요.");
return;
}
...
2. TS(2339) 에러
- Request에 정의되어 있지 않은 currentUserId property를 추가해주어 발생한 타입 에러이다.
Property 'currentUserId' does not exist on type 'Request'.ts(2339)
💡해결 방법
📌 같은 보면 좋은 공식 문서 자료 : Declaration Merging
import { Request, Response, NextFunction } from "express";
- 현재 express의 Request 타입을 import 해서 사용하고 있다. 이 type을 확장해주어야 한다.
1. tsconfig.json 수정
- tsconfig.json을 다음과 같이 수정해야한다. 이때 순서도 중요하다!
"typeRoots": ["./src/customType", "./node_modules/@types"]
1) 방법 : customType 폴더 생성
- src > customType > express > index.d.ts 파일을 만든다.
- 다음 코드를 추가한다.
import { Users } from "../../db/models/user";
declare global {
namespace Express {
interface Request {
currentUserId?: Users["pk_user_id"];
}
}
}
or
declare global {
namespace Express {
interface Request {
currentUserId?: string;
}
}
}
2) 방법 : node_modules 설정 변경
- node_modules > @types > express > index.d.ts 파일을 연다.
- 다음 코드를 추가한다.
declare global {
namespace Express {
interface Request {
currentUserId?: string;
}
}
}
📌 Reference
반응형