Skip to content

11 - Tuple to Object #3

@DEV4N4

Description

@DEV4N4
// your answers
// [P in T]: P 까지는 생각했지만 [P in T[number]]: P 까지는 생각 못함...
type TupleToObject<T extends readonly (string | symbol | number)[]> = {
  [P in T[number]]: P
}

1. 제네릭 T의 제한 (extends readonly (string | symbol | number)[])

  • T는 타입 매개변수로, 읽기 전용 튜플 타입이어야 한다고 명시합니다.
  • 튜플은 배열과 유사하지만, 요소의 타입과 개수가 고정된 데이터 구조입니다.
  • T는 배열의 요소 타입이 string, symbol, 또는 number여야 합니다. 이는 객체의 키로 사용할 수 있는 타입의 범위와 일치합니다.

2. 인덱싱 타입 T[number]

  • TypeScript에서 배열이나 튜플의 number 인덱스(T[number])는 배열의 요소 타입을 나타냅니다.
  • 예를 들어: T[number]는 튜플 T의 모든 요소를 유니언 타입으로 가져옵니다.
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const;
type ElementType = typeof tuple[number]; // 'tesla' | 'model 3' | 'model X' | 'model Y'

3. 매핑된 타입

  • P in T[number]를 사용해 T[number]의 각 요소(P)를 반복적으로 처리합니다.
  • 객체의 키와 값을 모두 P로 지정하여 결과적으로 객체의 키와 값이 동일한 타입이 되도록 만듭니다.

동작 과정

  1. 주어진 튜플에서 T[number]를 통해 모든 요소를 유니언 타입으로 가져옵니다.
  • 예: 'tesla' | 'model 3' | 'model X' | 'model Y'
  1. 매핑된 타입을 통해 각 요소를 순회하며 키와 값을 동일하게 설정합니다.
  • 결과적으로 객체 타입이 { 'tesla': 'tesla', 'model 3': 'model 3', ... }가 됩니다.

Metadata

Metadata

Assignees

No one assigned

    Labels

    answerShare answers/solutions to a question

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions