[NodeJS] Express Request Custom

이애진·2022년 7월 14일

Node

목록 보기
4/12
post-thumbnail

express와 typescript를 사용하다 보면, express가 제공하는 기본 req타입에 추가로 원하는 정보를 더 담아야한다 (custom types)

  1. Create a types folder in working directory
  2. Create a folder within the types folder with the name of the package you intend to extend
  3. Create an index.d.ts file in that folder
Sample Directory Structure

src/
   - types/
    - express/
     - index.d.ts
  1. add code to the index file
import express from "express";

export {};

declare global { // 타입이 없는 것을 새로 선언할 경우에 사용할 수 있다 (현재 전역으로 선언)
  namespace Express { // namespace를 하나로 모아서 export 한다
    interface Request { // Request interface
      [request name]: [type] // req.[name]: [type]
    }
  }
}

.d.ts 파일은 기존 js 모듈을 타입스크립트에서 사용하기 용이하도록 기존 js 모듈의 타입정보를 별도의 파일로 선언한 것이기 때문에 타입 선언만 할 수 있다

export {} 을 해주는 이유는 새로 선언한 타입을 global로 설정한 경우 external 모듈이어야하기 때문에 export를 사용하여 에러가 안나도록 한다
글로벌 객체를 확장하기 위해서 external, ambient 모듈이어야한다 (타입스크립트 컴파일러에 js에 대한 구현 환경에 대한 정보를 준다는 의미이다)

  1. update tsconfig.json file
{
  "compilerOptions": {
    "typeRoots" : ["./src/types", "./node_modules/@types"]
  }
}

node_modules/@types 도 같이 써주는 이유는 기본 제공하는 type들도 같이 쓰기 위함이다

ref

https://stackoverflow.com/questions/65848442/property-user-does-not-exist-on-type-requestparamsdictionary-any-any-pars

profile
Frontend Developer

0개의 댓글