C.W.K.
Stream
Lesson 04 of 05 · published

`noUncheckedIndexedAccess`

~7 min · strict-mode, no-unchecked-indexed-access, arrays

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"`arr[5]` 가 존재 안 할 수. Type system 이 그렇게 말해야."

뭐 추가

`noUncheckedIndexedAccess` 없으면 배열 index 접근이 배열 element 의 타입 가짐. arr: string[] 면 `arr[0]` 가 `string`. 근데 `arr[100]` 도 `string` 타입 — runtime 에 `undefined` 인데도. Type system 이 존재 안 하는 index 에 거짓말.

Flag 와 함께 모든 index 접근이 T | undefined 타입. `string[]` 의 arr[0] 가 `string | undefined`. 값 쓰기 전 undefined case 처리해야. Type system 이 마침내 runtime 현실과 match.

왜 strict 와 별개

Flag 가 `strict: true` 의 일부 아냐 — 기존 codebase 에 retrofit 하려면 모든 배열 index 접근 만져야. 새 코드엔 켜. Legacy 코드엔 migration 신중히 plan.

Object index signature 도

Flag 가 index-signature object 접근에도 영향. Flag 켜진 const obj: Record = {}; obj['anyKey'] 가 `User | undefined`. 옳음 — Record 가 빠진 key 에 undefined 반환 가능.

`noUncheckedIndexedAccess` 가 TypeScript 의 가장 정직한 flag. Index 접근이 undefined 반환 못 한다고 가장하기 거부. 강제하는 discipline — 쓰기 전 항상 narrow — 가 'undefined is not an object' runtime 버그 카테고리 통째 제거.

Code

Index 접근 — flag 와 함께와 없이·typescript
// noUncheckedIndexedAccess 없이 — 조용한 거짓말.
const arr: string[] = ['a', 'b'];
const x = arr[100];        // x: string — 근데 실제로 undefined
x.toUpperCase();           // runtime 에 크래시

// Flag 와 함께:
const arr2: string[] = ['a', 'b'];
const y = arr2[100];       // y: string | undefined
// y.toUpperCase();         // ❌ Object is possibly 'undefined'
if (y !== undefined) {
  y.toUpperCase();         // ✅ string 으로 narrow
}

// Object index signature 도 T | undefined 받음.
const map: Record<string, User> = { pippa: {} as User };
const u = map['pippa'];    // u: User | undefined
const u2 = map['missing']; // u2: User | undefined — 정확히

// Optional chaining 이 친구.
map['pippa']?.name;        // string | undefined

External links

Exercise

작은 프로젝트에 3 string 배열 선언, arr[10] 접근, 결과 사용. Flag 끄면 — 컴파일, runtime undefined. Flag 켜면 — undefined 처리할 때까지 compiler 거부. 너의 기존 프로젝트에서 이 flag 가 몇 자리 켤까?
Hint
아마 예상보다 많아. 모든 index 접근이 의심스러워. Index 후 항상-narrow discipline 이 빠르게 second nature.

Progress

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

댓글 0

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

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