ts-pattern 타입 추론 패턴 라이브러리
ts-patern 간단 예시 및 정리
작성일 : 2025.02.06
TIL
ts-pattern
- TypeScript를 위한 타입 추론 패턴 매칭 라이브러리
기본 사용 예시
//github 첫 화면에 있는 예시 코드 import { match, P } from 'ts-pattern'; type Data = | { type: 'text'; content: string } | { type: 'img'; src: string }; type Result = | { type: 'ok'; data: Data } | { type: 'error'; error: Error }; const result: Result = ...; const html = match(result) .with({ type: 'error' }, () => <p>Oups! An error occured</p>) .with({ type: 'ok', data: { type: 'text' } }, (res) => <p>{res.data.content}</p>) .with({ type: 'ok', data: { type: 'img', src: P.select() } }, (src) => <img src={src} />) .exhaustive();
match
를 사용해서switch
문 처럼 결과를 분기할 수 있다.P
(Pattern)의 여러 메서드를 이용해서 쉽게 결과를 도출할 수 있다..with({ type: 'ok', data: { type: 'img', src: P.select() } }, (src) => <img src={src} />
- (depth가 깊은 값인데 P.select()로 간단하게 원하는 값을 전달 받고 있다.)
똑같은 코드를 ts-pattern 없이 구현한다면
type Data = | { type: 'text'; content: string } | { type: 'img'; src: string }; type Result = | { type: 'ok'; data: Data } | { type: 'error'; error: Error }; const result: Result = { type: 'ok', data: { type: 'img', src: 'image.jpg' } }; const getHtml = () => { switch (result.type) { case 'error': return (<p>Oups! An error occured</p>); case 'ok': if(result.data.type === 'text') { return (<p>{result.data.content}</p>); } else if (result.data.type === 'img') { return (<img src={result.data.src} />); } default: return null; } }; const html = getHtml();
- 가독성 향상을 위해 중첩 조건문을 2가지 형식으로 나눠서 표시
- 1단계 조건문 : switch
- 2단계 조건문 : if문
ts-pattern
을 썼을 때exhaustive()
함수 실행 시점에서 모든 케이스가 입력되었는지 확인이 가능하지만,switch
문으로는 누락이 될 수도 있음- 중첩 조건문이 들어가서 코드가 복잡함
- (lodash, ramda.js로 더 간결하게 표현할 수는 있지만 협업 시 구성원들에게는 러닝커브가 있을 가능성이 있다.)
그 외
P.union
,P.not
등 유용한 패턴을 미리 구현해 두어, 간편하고 안전하게 타입 추론을 할 수 있다.
참조
- https://github.com/gvergnaud/ts-pattern, ts-pattern github, 2025.02.06 열람