NonNullable을 활용한 타입 가드
NonNullable
은 타입스크립트에서 제공하는 유틸리티 타입으로 제네릭으로 받는 T가null
또는undefined
일 때never
를 반환하는 타입이다.
type NonNullable<T> = T extends null | undefined ? never : T;
- null을 가질 수 있는(Nullable) 값의 null 처리는 자주 사용되는 타입 가드 패턴의 하나이다. 일반적으로 if문을 사용해서 null 처리 타입 가드를 적용하지만,
is
키워드와NonNullable
타입으로 타입 검사를 위한 유틸 함수를 만들어서 사용할 수 있다. - 매개변수 value가
null
이나undefined
가 아니라면 타입이 좁혀진다.
function NonNullable<T>(value: T): value is NonNullable<T> { return value !== null && value !== undefined; }
Promise.all에 NonNullable 적용
- shopAdCampaignList는
null
을 포함하고 있기 때문에 순회할 때마다if
문을 사용하여 타입 가드를 반복적으로 수행해야 한다. - NonNullable 함수로 필터링하면 필터링 효과와 타입을 좁히는 효과를 동시에 누릴 수 있다.
type AdCampaign = {}; class AdCampaignAPI { static async operating(shopNo: number): Promise<AdCampaign[] | null> { try { const res = await fetch(`/ad/shopNumber=${shopNo}`); return res.json(); } catch (error) { return null; } } } async function getFn() { const shopList = [ { shopNo: 100, category: 'chicken' }, { shopNo: 101, category: 'pizza' }, { shopNo: 102, category: 'noodle' }, ]; const shopAdCampaignList = await Promise.all( shopList.map((shop) => AdCampaignAPI.operating(shop.shopNo)) ); // (AdCampaign[] | null)[] const shopAds = shopAdCampaignList.filter(NonNullable); // AdCampaign[][] }
'TypeScript' 카테고리의 다른 글
[TS] Record 원시 타입 키 개선 (1) | 2025.01.30 |
---|---|
[TS] 불변 객체 타입 (0) | 2025.01.29 |
[TS] 유틸리티 타입 (0) | 2025.01.27 |
[TS] 조건부 타입 (0) | 2025.01.26 |
[TS] 식별할 수 있는 유니온, Exhaustiveness Checking (1) | 2025.01.25 |