• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    해결됨

FlatArray의 ReadonlyArray의 요소 추론

23.06.18 17:00 작성 조회수 299

1

 

type FlatArray<Arr, Depth extends number> = {
    "done": Arr,
    "recur": Arr extends ReadonlyArray<infer InnerArr>
        ? FlatArray<InnerArr, [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][Depth]>
        : Arr
}[Depth extends -1 ? "done" : "recur"];

이 flat 함수 타입의 type에서

"recur": Arr extends ReadonlyArray<infer InnerArr>

요소의 타입을 추론한다 이 부분이 이해가 잘 안갑니다.

interface ReadonlyArray<T> {

    /**
     * Calls a defined callback function on each element of an array. Then, flattens the result into
     * a new array.
     * This is identical to a map followed by flat with depth 1.
     *
     * @param callback A function that accepts up to three arguments. The flatMap method calls the
     * callback function one time for each element in the array.
     * @param thisArg An object to which the this keyword can refer in the callback function. If
     * thisArg is omitted, undefined is used as the this value.
     */
    flatMap<U, This = undefined> (
        callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray<U>,
        thisArg?: This
    ): U[]


    /**
     * Returns a new array with all sub-array elements concatenated into it recursively up to the
     * specified depth.
     *
     * @param depth The maximum recursion depth
     */
    flat<A, D extends number = 1>(
        this: A,
        depth?: D
    ): FlatArray<A, D>[]
  }

 

infer InnerArr에 해당하는 ReadonlyArray의 T 제네릭을 추론할 수 있는 부분이 ReadonlyArray interface 안에 전혀 없어보입니다...! ㅠ

 

 

 

 

 

답변 1

답변을 작성해보세요.

1

infer는 내부 구현를 볼 필요가 없습니다. 그냥 T의 구체적인 타입 자체를 가져오는 겁니다.

ReadonlyArray<string>이면 innerArr은 string으로 추론되는거고요.

답변 감사합니다!