프로그래밍/TypeScript

typescript에서 runtime interface 체크하기

p-a-r-k 2023. 2. 3. 13:21
반응형

Interface type check at runtime with Typescript

 

타입스크립트에서 메서드로 받는 parameter가 2가지의 인터페이스로 오는 경우가 생겼다.

한가지는 주소검색으로 특정 위치목록을 받을때는 A라는 interface이고,

주소가 없는경우 서버에 등록후 리턴받을때는 B라는 interface 형태로 받게된다.

 

이때, A일경우에는 A에만 있는 속성인 c를 사용하고싶고,

B인경우에는 B에만 있는 속성인 d.e 를 사용하고 싶었다.

 

그래서 A타입인지를 구분해주는 함수를 하나 만들었다.

export function isAType(workingSpot: A | B): workingSpot is A {
  if (!workingSpot) return false;
  return (<A>workingSpot).c !== undefined;
}

B인경우 c라는 속성은 없을테니 parameter가 A라는 가정을 하고 boolean을 반환해준다.

 

if (isAType(workingSpot)) {
  return workingSpot.c;
}
return workingSpot?.d?.e || '';

사용할 땐, A인경우와 나머지인경우를 생각하여 사용하면된다.

반응형