Index signature는 이름을 미리 알 수 없을 때 프로퍼티의 타입을 기술합니다 — 키가 동적인 딕셔너리/map을 모델링합니다.
ts
interface StringMap {
[key: string]: ;
}
: = { : , : };
scores. = ;
scores.;
scores.;
Index signature는 이름을 미리 알 수 없을 때 프로퍼티의 타입을 기술합니다 — 키가 동적인 딕셔너리/map을 모델링합니다.
interface StringMap {
[key: string]: ;
}
: = { : , : };
scores. = ;
scores.;
scores.;
평범한 index signature에서는 컴파일러가 모든 키가 존재한다고 가정하므로, scores.typo가 실제로 런타임에 undefined여도 number로 타이핑됩니다. noUncheckedIndexedAccess를 켜면 이를 고칩니다:
// noUncheckedIndexedAccess: true 일 때
scores.math; // number | undefined → 없는 경우의 처리를 강제
interface Config {
name: string; // 알려진 프로퍼티
[key: string]: string | number; // 추가로 임의의 키들
}
모든 이름 있는 프로퍼티는 index signature의 값 타입에 대입 가능해야 합니다.
type Scores = Record<string, number>; // index signature와 동일
type Roles = Record<"admin" | "user", boolean>; // 제약된 키
Record는 관용적인 약식이며 제한된 키 union을 지원합니다 — 평범한 [key: string]은 할 수 없습니다.
Index signature는 진짜로 동적 키를 가진 객체(룩업 테이블, 캐시, 파싱된 JSON map)를 모델링합니다.
안전성 주의점(noUncheckedIndexedAccess)을 알아두고 가독성을 위해 Record<K, V>를 선호하세요 — 그리고 키가 진짜 열려 있고 실제 순회/크기 의미가 필요하면 Map을 선호하세요.