기본적으로 express.js에서 Request body의 타입은 미리 정의되지 않는다. 그렇다면 바디에 담길 타입을 개발 과정에서 미리 정의해두고 싶다면 어떻게 해야할까?
전역 모듈 선언 사용
typescript에선 기본적으로 개발자가 특정 모듈에 대한 정의를 작성하거나, 수정할 수 있는 방법을 제공한다.
프로젝트의 루트 디렉토리에 @types 폴더를 만들고, 다음과 같이 body의 타입을 정의할 수 있다.
declare module "express" {
interface Request<T> {
T?: T;
}
}
}
Custom Interface 작성
Request에 대한 정의만 새로 작성하고 싶다면 Custom Interface를 사용할 수 있다.
import { Request } from "express";
export interface CustomRequest<T> extends Request {
body?: T;
}
두 경우 다 실제로 사용할 때는 다음과 같이 사용하면 된다.
async (req: CustomRequest<UserType>, res: Response, next: NextFunction) => {
const { body } = req;
console.log(typeof(body), typeof(body.id)); // body는 UserType
const user: UserType = await userservice.post(body);
const result: ResponseType<UserType> = {
message: "회원가입에 성공하였습니다.",
data: user,
};
res.status(201).json(result);
}
'개발 > Express' 카테고리의 다른 글
[express] 유저 crud와 토큰을 이용한 로그인 구현 (0) | 2023.07.23 |
---|---|
[express] Schema와 Model을 생성하고 데이터 저장하기 (0) | 2023.07.08 |
[express] 데이터베이스에 연결하기 (0) | 2022.03.30 |
[express] 필요한 api 라우팅하기 (0) | 2022.03.07 |
[express] 개요 (1) | 2022.03.05 |