Promise.all 타입 정의

그니·2023년 9월 28일
0
post-thumbnail

인프런 - 제로초 - [리뉴얼] 타입스크립트 올인원 : Part1. 기본 문법편

/**
     * Creates a Promise that is resolved with an array of results when all of the provided Promises
     * resolve, or rejected when any Promise is rejected.
     * @param values An array of Promises.
     * @returns A new Promise.
     */
all<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: Awaited<T[P]> }>;
  1. T 제네릭의 타입은 all의 파라미터인 values의 타입으로 추론되어 지정된다.
  2. T 제네릭은 unknown[] | [] 합집합의 서브 집합 이여야 한다.
  3. 배열을 keyof 로 추출할 경우 index가 반환된다.
  4. 다만, readonly 키워드와 함께 또는 as const로 상수화 해야 한다.
    1. 길이가 고정되지 않을 경우 number[] 로 좁혀진다.
  5. key 추출용으로 사용한 readonly는 해제한다.
  6. 파라미터로 받은 Promise들의 리턴 타입을 추출하기 위해 Awaited에 추출한 Promise를 타입 파라미터로 보낸다.
type Awaited<T> =
    T extends null | undefined ? T : // special case for `null | undefined` when not in `--strictNullChecks` mode
        T extends object & { then(onfulfilled: infer F, ...args: infer _): any } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped
            F extends ((value: infer V, ...args: infer _) => any) ? // if the argument to `then` is callable, extracts the first argument
                Awaited<V> : // recursively unwrap the value
                never : // the argument to `then` was not callable
        T; // non-object or non-thenable
  • Awaited는 제네릭을 명시적으로 받는다.
  • 점진적으로 삼항연산자를 통해 타입을 좁혀나간다.
  1. T가 null 또는 undefined인가?
    1.1 T 타입 반환
  2. T가 object이면서 thenable 시그니처에 충족 되는가?
    2.1 여기서 infer로 Promise 성공 시 호출 되는 콜백 함수를 F로 추론해놓는다.
  3. F가 thenable 시그니처에 충족 되는가?
    3.1 여기서 then이 호출 될 때 전달되는 value의 타입을 V로 추론해놓는다.
  4. 더 이상 then을 호출할 수 없을때까지 반복한다.
Promise.reject('test').then(value => value).then(value => value);
  • 값이 thenable -> then 메서드를 호출할 수 있는지
  • 호출할 수 있으면서 콜백의 시그니처가 (value, ...args) => any 인지
  • value에 대해서 한번 더 thenable인지 추론

0개의 댓글