inflearn logo
강의

Course

Instructor

Applying TypeScript to React while learning while making web games

express response 타입

210

haruharu

43 asked

0

type JsonBody = {
  success: boolean;
  data: any;
};

declare global {
  namespace Express {
    export interface Response {
      json: (body: JsonBody) => this;
      test: (body: JsonBody) => this;
    }
  }
}

export {};

라이브러리 버전

express 4.18.2

@types/express 1.17.17

 

get, post 등 모든 요청에서 응답으로 res.status(200).json({success:true, data: []}) 이런 형식으로 코드 자동완성 기능 이용하려고 위와 같이 Express Response에 json 타입을 오버로딩 했는데 res.status(200).json 코드를 입력하면 오버로딩한 타입은 자동완성추천에 뜨지않고 express 자체에서 작성해둔 타입 json(body?: any): Response<any, Record<string, any>, number> 이런 타입만 뜹니다.

json 아래에 작성한 test는 res.status(200).test 작성시 자동완성 추천도 잘되고 객체에 success랑 data 입력하게 자동완성 기능이 잘 동작하는데 json만 동작이 안됩니다. 어떻게하면 해결할 수 있을까요?

react typescript

Answer 1

0

zerocho

test 메서드는 기존에 없는 메서드를 추가한 것이라 declaration merging이 되는데, json 메서드는 기존에 있는 것을 덮어씌우는 것이라 안 됩니다. declaration merging으로는 기존 속성을 덮어씌울 수는 없습니다.

https://stackoverflow.com/a/66567805/4464863

이런 식으로 Response에 있는 Generic을 활용해서 json body를 타이핑하셔야 합니다.

0

haruharu

예시1

interface Add {
  (x: number, y: number): number;
  (x: string, y: string): string;
}

const add: Add = (x, y) => x + y;

예시2

declare function add(x: number, y: number): number;
declare function add(x: string, y: string): string;

예시1, 2 처럼 오버로딩해서 타입 작성하고 상황에 맞게 타입을 사용하는게 가능한걸로 아는데 두가지 예시랑 express 질문했던거랑은 다른건가요?

 

0

zerocho

네 올려주신 건 오버로딩이고, 기존에 있는걸 덮어쓰는 건 선언 병합입니다. 다른 특성입니다.

기존 코드에

interface Add {

(x: number, y: number): strinf;

(x: string, y: string): number;

}

를 추가로 더 선언한 상황이라고 보시면 됩니다.

createRoot

0

285

1

babel-loader질문입니다! 왜쓰는지 궁금합니다!

0

685

1

undefined 처리

0

493

1

compilerOptions lib 관련

0

329

1

event type 찾기

0

324

1

정확한 type vs 가독성

0

292

1

useRef에 대해 질문드립니다.

0

305

1

tsx파일에서 에러 표시

0

864

1

Props type 질문드립니다.

0

227

1

webpack.config.ts/ Could not find a declaration file for module '@pmmmwh/react-refresh-webpack-plugin'.

0

590

1

18버전에서의 ReactDOM.render

1

658

1

깃허브에 react-router@6 업데이트 해주신 코드 질문드립니다.

0

294

1

2강 끝말잇기 npx webpack 오류가 질의사항

0

408

1

Property 'render' does not exist on type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'.

0

716

1

webpack.config.ts import 할 때 에러좀 봐주세요!!

0

307

1

React.FC에 대해 궁금합니다.

0

701

1

가위바위보 interval 타입과 이벤트타입에 관한질문

0

343

1

npm run dev 실행은 성공적으로 되는데

0

677

2

redux 유료강좌를 듣고 와야 되는지 여쭈어보려고 합니다.

0

320

1

git 내용과 강의 내용이 달라서 여쭈어봅니다.

0

223

1

Ball.tsx 타이핑

0

324

2

react-router 버젼 업그레이드 변경사항 문의

0

286

2

리액트 타입스크립트 공식문서

0

338

1

button 클릭 할 떄 마다 더보기/닫기 에러

0

856

1