C.W.K.
Stream
Lesson 05 of 05 · published

`Awaited<T>` 와 `NonNullable<T>`

~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 가 Promise unwrap. NonNullable 이 null 과 undefined strip. 주마다 쓸 작은 utility 2개."

`Awaited` — 재귀적으로 Promise unwrap

Awaited<Promise<string>> 가 `string`. Awaited<Promise<Promise<number>>> 도 `number` — Awaited 가 값이 더 이상 Promise 아닐 때까지 recurse. JavaScript runtime 과 match: `await Promise.resolve(Promise.resolve(x))` 가 `Promise` 아니라 `x` 로 resolve.

Awaited 가 TypeScript 4.5 에 정확히 옛 `Promise` 모델이 중첩 Promise 를 정확히 처리 못 해서 추가됨. `ReturnType` 쓸 어디든, 실제 resolved 타입 얻으려면 `Awaited` 로 wrap 하고 싶어할 거.

`NonNullable` — null 과 undefined strip

NonNullable<string | null | undefined> 가 `string`. Utility 가 union 에 distribution 써서 null 이나 undefined 인 어떤 멤버든 제거. 가능 nullable 타입 있고 (체크 후) 안전하다 주장하고 싶을 때 유용.

Awaited 와 NonNullable 이 외과적 타입 stripper. 한 번에 한 wrapper 풀어 — 첫째 Promise, 둘째 null/undefined. ReturnType 과 compose 해서 함수 참조에서 정확한 타입 빌드.

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> 반환할 수 있는 함수 주어지면, '그것이 resolve 하는 거의 non-null 버전' 의 타입 써. Type system 이 Awaited 나 NonNullable 로 wrap 잊은 case 잡는지 확인.
Hint
type SafeLoaded = NonNullable<Awaited<ReturnType<typeof load>>>. 순서 중요: 먼저 Awaited 가 Promise unwrap, 그다음 NonNullable 이 null strip.

Progress

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

댓글 0

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

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