타입명["프로퍼티명"] 또는 타입명[숫자] 형태로 사용함.인덱스드 엑세스 타입은 인덱스를 이용해 다른 타입내의 특정 프로퍼티의 타입을 추출하는 타입임. 객체, 배열, 튜플에 모두 사용할 수 있음.
interface Post {
title: string;
content: string;
author: {
id: number;
name: string;
age: number;
};
}
function printAuthorInfo(author: Post["author"]) {
console.log(`${author.id} - ${author.name}`);
}
Post["author"]는 Post 타입에서 author 프로퍼티의 타입을 추출함.const authorKey = "author";
function printAuthorInfo(author: Post[authorKey]) { // ❌ 오류 발생
console.log(`${author.id} - ${author.name}`);
}
중첩 접근도 가능함.
function printAuthorInfo(authorId: Post["author"]["id"]) {
console.log(authorId);
}
type PostList = Post[];
const post: PostList[number] = {
title: "게시글 제목",
content: "게시글 본문",
author: {
id: 1,
name: "이정환",
age: 27,
},
};
PostList[number]는 배열의 요소 타입을 추출함.PostList[0]처럼 숫자 리터럴을 써도 동일하게 동작함.type Tup = [number, string, boolean];
type Tup0 = Tup[0]; // number
type Tup1 = Tup[1]; // string
type Tup2 = Tup[2]; // boolean
type Tup3 = Tup[number]; // number | string | boolean
number 인덱스를 넣으면 모든 요소의 유니온 타입이 추출됨.[number], 튜플은 [숫자] 또는 [number]로 유니온 처리됨.