inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[리뉴얼] 타입스크립트 올인원 : Part1. 기본 문법편

완전 복잡한 타입 분석하기(flat 편)

FlatArray의 ReadonlyArray의 요소 추론

해결된 질문

453

극복밤송

작성한 질문수 11

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 안에 전혀 없어보입니다...! ㅠ

 

 

 

 

 

typescript

답변 1

1

제로초(조현영)

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

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

0

극복밤송

답변 감사합니다!

데코레이터가 현재도 자주 쓰이는 문법인가요?

0

81

2

유틸리티 타입 실제로 구현은 못해도 하나씩 외우면 실무할 때 지장 없겠죠?

0

66

1

매핑 타입은 type에서밖에 안된다고 하네요?

0

65

2

자바에서의 오버로딩과 같은 개념이라고 생각해도 되나요?

0

69

2

filter 함수 반환 타입 네로잉 질문

0

74

2

map<U>(callbackfn: ....) 할때 U는 왜 여기 있는거에요??

0

47

2

ts 컴파일을 위한 type 라벨링 부분

0

46

1

concat 함수 타입 구현 중 질문 있습니다!

0

100

2

filter 메소드 질문

0

53

1

forEach 제네릭 관련 문의

0

60

1

타입 추론 시 가장 넓은 범위로 추론이 되는 건가요?

0

165

1

enum이 javascript로 트랜스파일링될때 사라진다하셨는데요

0

207

1

함수 파라미터 타입 정의 시 ...args: any[]와 ...args: any 의 차이

0

223

1

Flat type에서 ReadonlyArray 타입을 사용하는 이유?

0

157

1

bind type 질문

1

149

1

Lowercase type 관련 질문

0

152

1

key-value 타입 자동추론 질문드립니다

0

266

1

타입스크립트 교과서, p131

0

266

1

타입스크립트 교과서 p122 forEach 메서드 질문

0

232

1

타입스크립트 교과서 p116 , 코드에러남

1

269

1

타입스크립트 교과서 p112 , 코드가 안읽힙니다..

0

266

1

타입스크립트 교과서 p83

1

184

1

타입스크립트교과서 p39 쪽 코드가 이해가 안되요

1

227

1

class 에서 ts의 private vs js의 private field( # )

0

339

1