일단 시작하는 IT개발 블로그
  • 3. Tuple of Object
    2023년 08월 09일 00시 35분 21초에 업로드 된 글입니다.
    작성자: sooooong_minseok
    type TupleToObject<T extends readonly any[]> = any
    
    /* _____________ 테스트 케이스 _____________ */
    import type { Equal, Expect } from '@type-challenges/utils'
    
    const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
    const tupleNumber = [1, 2, 3, 4] as const
    const tupleMix = [1, '2', 3, '4'] as const
    
    type cases = [
      Expect<Equal<TupleToObject<typeof tuple>, { tesla: 'tesla'; 'model 3': 'model 3'; 'model X': 'model X'; 'model Y': 'model Y' }>>,
      Expect<Equal<TupleToObject<typeof tupleNumber>, { 1: 1; 2: 2; 3: 3; 4: 4 }>>,
      Expect<Equal<TupleToObject<typeof tupleMix>, { 1: 1; '2': '2'; 3: 3; '4': '4' }>>,
    ]
    
    // @ts-expect-error
    type error = TupleToObject<[[1, 2], {}]>

    키워드1. 튜플

    https://yamoo9.gitbook.io/typescript/types/tuple

    키워드2. readonly // as const // tuple

    • readonly: 읽기 전용 타입으로 변경을 막음. 컴파일 타임에서만 체크되며, runtime에는 영향 없음.
    • as const: 리터럴 타입으로 요소를 추론하도록 강제함. 변경을 막고, 해당 값들이 상수로 취급됨.
    • tuple: 배열의 특수한 형태로, 요소의 개수와 타입이 고정됨. 특정 위치에 특정 타입의 값을 가지도록 강제함.

    키워드3. 

    [P in T[number]] : P: 이 부분은 TypeScript의 맵드 타입(mapped type) 문법을 사용한 것으로 객체의 프로퍼티들을  맵드 타입은 객체의 프로퍼티들을 새로운 형태로 변환하는 기능을 제공합니다.

    여기서 T[number]는 T 타입의 모든 요소들을 유니온 타입으로 추출합니다. 예를 들어, T가 ['tesla', 'model 3', 'model X', 'model Y']라면, T[number]는 'tesla' | 'model 3' | 'model X' | 'model Y'가 됩니다.

    따라서 [P in T[number]] : P는 각 요소를 반복하면서, 해당 요소를 프로퍼티 이름으로 사용하고 해당 요소 자체를 값으로 갖는 객체를 만드는 것을 의미합니다. 즉, TupleToObject 타입은 아래와 같이 변환됩니다.

    정답

    type TupleToObject<T extends readonly any[]> = {
      [P in T[number]] : P
    }

    '프로그래밍언어 > typescript' 카테고리의 다른 글

    4. First of Array  (0) 2023.08.09
    2. Readonly  (0) 2023.08.02
    1. Pick  (0) 2023.07.22
    댓글