C.W.K.
Stream
Lesson 03 of 06 · published

Indexed Access: `T[K]`

~8 min · type-manipulation, indexed-access, type-extraction

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"`T[K]` 가 property 타입 읽는 법, `obj[key]` 가 값 읽는 법과 같음."

Indexed-access 타입 operator

T[K] 가 K key 의 T 의 property 타입으로 평가. { id: number; name: string }['id'] 가 `number`. { id: number; name: string }['name'] 가 `string`. 문법이 runtime property 접근 mirror; 차이는 이건 타입 레벨에서 일어난다는 거.

K 가 단일 key 거나 key 의 union 일 수: User['id' | 'name'] 가 `number | string`. 결과가 그 key 들의 값 타입의 union.

배열의 숫자 indexed access

string[][number] 가 `string` — string 배열의 element 타입. [number, string][0] 가 `number` — tuple 의 첫 위치. [number, string][number] 가 `number | string` — 모든 위치의 union.

Tuple 엔 integer literal 접근이 그 위치의 타입 줌. 배열엔 `[number]` 이 element 타입 줌. 타입 레벨에서 배열 element 얘기하는 canonical 방법.

keyof + indexed access 패턴 (재방문)

T[keyof T] 가 T 의 모든 value 타입의 union. 이 쌍이 너무 흔해서 docs 에 이름 있어: 'keyof 통한 indexed access.' Mapped 타입과 결합, 대부분 utility 타입이 object 모양 탐색하는 법.

Indexed access 가 property 접근의 타입-레벨 사촌. `T[K]` 읽을 수 있게 되면 대부분 고급 TypeScript 타입 정의 navigation 가능.

Code

Indexed access — 단일, union, 배열, tuple·typescript
interface User { id: number; name: string; email: string }

// 단일 key.
type UserId = User['id'];         // number
type UserName = User['name'];     // string

// Key 의 union.
type UserIdOrName = User['id' | 'name'];  // number | string
type AllValues = User[keyof User];        // number | string (여기서 같음)

// Tuple — 위치 indexed access.
type Pair = [number, string];
type First = Pair[0];             // number
type Second = Pair[1];            // string
type Any = Pair[number];          // number | string (모든 위치)

// 배열 — [number] 통한 element 타입.
type Element = User[][number];    // User
type FirstUser = User[][0];       // User (어떤 non-negative integer 든 작동)

External links

Exercise

type Vehicle = { make: string; year: number; wheels: 2 | 4 } 주어지면, indexed access 통해 각 필드 타입 추출. 그다음 VehicleValues = Vehicle[keyof Vehicle] derive. 각각 수동 hover 와 비교.
Hint
Vehicle['make'], Vehicle['year'], 등이 필드 타입과 match. keyof+indexed access 쌍이 string | number | (2 | 4) 줘 — compiler 가 string | number | 2 | 4 로 단순화 가능.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.