ts-pattern은 패턴 매칭을 Typeacript 환경에서 사용할 수 있는 라이브러리다. 패턴 매칭은 주로 함수형 프로그래밍 언어에서 조건 및 분기 구현을 위해 사용한다고 한다.
React 컴포넌트에서 삼항 연산자 등을 사용해 조건부 렌더링 구현을 하다가 대안이 없을까 싶어 찾아보다가 발견한 라이브러리다. Github에 걸려있는 적용 이전과 이후를 비교한 예시를 보고 혹해버렸다. 회사 프로젝트에 적용할 수 있을지 검토해보고 내린 결론과 그 근거를 정리해보았다.
예시 코드
지도의 마커를 정의하기 위해 아래와 같이 타입이 있다고 하자.
export type Path = "Start" | "Middle" | "End";
export type Marker = {
iconType: "Place" | "Path"; // 마커의 종류는 두 가지로, Place 마커의 경우에는 pathType을 가지지 않는다.
pathType?: Path;
};
ts-pattern을 적용하기 이전의 코드는 아래와 같다.
const getPathType = (marker: Marker): Path | undefined => {
if (marker.iconType === "Path") {
if (marker.pathType === "Start") {
return "Start";
}
if (marker.pathType === "Middle") {
return "Middle";
}
if (marker.pathType === "End") {
return "End";
}
}
return undefined;
};
export const BeforePattern = () => {
const marker: Marker = {
iconType: "Path",
pathType: "Start",
};
return <div>{getPathType(marker)}</div>;
};
중첩된 if문을 통해 구현했다.
ts-pattern을 적용할 시 아래와 같은 구현이 가능하다.
export const AfterPattern = () => {
const marker: Marker = {
iconType: "Pathway",
pathType: "Start",
};
return (
<div>
{match(marker)
.with({ iconType: "Pathway", pathType: "Start" }, () => "Start")
.with({ iconType: "Pathway", pathType: "Middle" }, () => "Middle")
.with({ iconType: "Pathway", pathType: "End" }, () => "End")
.otherwise(() => undefined)}
</div>
);
};
이외에도 놓치는 분기 케이스가 없도록 exhaustive()
를 추가하거나, 분기 및 type narrowing을 위해 when()
등을 유용하게 쓸 수 있을 것 같다.