[NodeJs][Typescript] : Error 객체 타입을 재정의하기

Darcy Daeseok YU ·2023년 7월 9일
0

Node 공부중 Error객체에 status property가 없어서 에러가나왓다.
방법은 여러가지 인데 ...
Global정의하니까 제일 깔끔한듯

해결안 1 : Error객체는 다른 라이브러리처럼 설치형이아닌 이미 노드 전역에 정의된 객체이며 타입을 가지고 있기 때문에 global로 재 선언한다.

type.d.ts 파일에 아래와 같이 정의

declare global

declare global {

	interface Error {
    	status? : number;
        }
} 


정의한 후 필 히 

export {}  << 추가해주자.

번외로 설치한 라이브러리에 프로퍼티와 타입을 추가해야한다면
아래와 같이 재정의해준다.

import "라이브러리"

declare module '라이브러리명' {
	interface "라이브러리타입명" {
    	aaa ? : string; 
       }
}

실제 예시 : req.session 객체에 user 오브젝트 타입을 재정의 

import "express-session"

delcare module "express-session"{
	interface SessionData {
    	user: { {key : string] : any }
    }
}

해걸안 2 : interface를 새로 만든다.
원하는 폴더에 types.ts 을 만들고 아래와 같이 정의하고
필요할때 그때그때 불러서 쓰자.

export interface INewTypedError extends Error {
	status?: number;
}

runtime error 조치
type.d.ts : export {} 추가
tsconfig.json "ts-node": { "files": true } 추가

	declare global {} 

	export {} //추가  

tsconfig.json
추가:

{
  "ts-node": { "files": true },
  "compilerOptions": {},
}
profile
React, React-Native https://darcyu83.netlify.app/

0개의 댓글