bh2980.dev

189 - Awaited

  • #Type Challenges
  • #TypeScript

질문

Promise와 같은 타입에 감싸인 타입이 있을 때, 안에 감싸인 타입이 무엇인지 어떻게 알 수 있을까요?

예시: 들어 Promise<ExampleType>이 있을 때, ExampleType을 어떻게 얻을 수 있을까요?

type ExampleType = Promise<string>

type Result = MyAwaited<ExampleType> // string

// !collapse(1:30) collapsed
/* _____________ 테스트 케이스 _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type X = Promise<string>
type Y = Promise<{ field: number }>
type Z = Promise<Promise<string | number>>
type Z1 = Promise<Promise<Promise<string | boolean>>>
type T = { then: (onfulfilled: (arg: number) => any) => any }

type cases = [
  Expect<Equal<MyAwaited<X>, string>>,
  Expect<Equal<MyAwaited<Y>, { field: number }>>,
  Expect<Equal<MyAwaited<Z>, string | number>>,
  Expect<Equal<MyAwaited<Z1>, string | boolean>>,
  Expect<Equal<MyAwaited<T>, number>>,
]

선행 지식

  1. Promise<T>

    비동기 연산의 결과값으로 나중에 T를 반환하는 객체 타입. 실제 자바스크립트의 비동기 객체 타입이다.

  2. PromiseLike<T>

    interface PromiseLike<T> {
      then(
        onfulfilled?: (value: T) => any,
        onrejected?: (reason: any) => any
      ): any
    }

    실제 Promise 객체는 아니지만, then 메서드를 가지고 있고, then의 콜백이 T를 받는다면 PromiseLike으로 취급한다. 타입으로만 존재하지만 이 타입을 사용한다고 해서 실제 런타임에서 Promise의 동작을 보장하진 않는다.

풀이