본문 바로가기
C.W.K.
Stream
Lesson 05 of 05 · published

Awaited와 NonNullable: 포장과 빈 가능성 벗기기

~7 min · utility-types, awaited, non-nullable, promises

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Awaited는 비동기 포장을, NonNullable은 null과 undefined 가능성을 벗겨."

Awaited는 await의 타입 동작을 닮아

Awaited<Promise<string>>은 string이야. Promise가 여러 겹이어도 최종 값에 닿을 때까지 재귀적으로 벗기고, 입력이 Promise가 아니면 원래 타입을 그대로 돌려줘. JavaScript의 await가 thenable을 평평하게 다루는 동작을 타입으로 표현한 도구야.

비동기 함수가 최종적으로 돌려줄 값은 Awaited<ReturnType<typeof load>>로 얻을 수 있어. Promise를 직접 다시 적지 않으므로 함수 계약이 바뀌어도 함께 따라간다.

NonNullable은 두 빈 값을 제거해

NonNullable<string | null | undefined>은 string이야. 유니언의 각 구성원에 조건을 분배해 null과 undefined를 never로 바꾸고 나머지만 남기는 방식으로 생각할 수 있어.

중요한 점은 타입만 제거한다고 실행값이 검증되는 것은 아니라는 거야. 값이 실제로 null이 아님을 조건문이나 검사 함수로 증명한 뒤 좁혀진 결과를 반환해야 해. 단언으로 NonNullable을 억지로 맞추면 빈 가능성을 숨길 뿐이야.

유틸리티 타입은 증명의 결과를 표현하지 증명을 대신하지 않아. 먼저 실행 코드로 포장과 빈 가능성을 처리하고 타입이 그 사실을 따라가게 해.

Code

Awaited 와 NonNullable·typescript
// Awaited — 재귀 Promise unwrap.
type A = Awaited<Promise<string>>;             // string
type B = Awaited<Promise<Promise<number>>>;    // number — 재귀
type C = Awaited<string>;                       // string — pass-through

// 흔한 체인: Awaited + ReturnType.
async function load(): Promise<User> { /* ... */ return {} as User }
type LoadedUser = Awaited<ReturnType<typeof load>>;   // User

// NonNullable — null 과 undefined strip.
type D = NonNullable<string | null>;            // string
type E = NonNullable<number | undefined>;       // number
type F = NonNullable<string | null | undefined>; // string

// 체크 후 유용.
function must<T>(v: T | null | undefined): NonNullable<T> {
  if (v === null || v === undefined) throw new Error('null');
  return v;
}

External links

Exercise

Promise<User | null>을 반환하는 함수에서 성공 값의 null 아닌 타입을 파생해. Awaited나 NonNullable을 하나 빼면 어떤 사용이 실패하는지도 확인해.
Hint
먼저 Awaited로 Promise를 벗기고, 그 결과에 NonNullable을 적용해 null 가능성을 제거해. 두 단계의 순서를 타입 별칭에서 그대로 보여 줘.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인 — 댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.