반응형
타입스크립트에서의 인덱스드 액세스 타입
만약에 밑과 같은 Post라는 객체가 있을 때 Post안에 author를 출력한다고 치자
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
//인덱스드 액세스 타입
interface Post {
title: string;
content: string;
author : {
id: number;
name: string;
};
}
const post: Post {
title: computer ko,
content: typescript,
author: {
id: 1,
name: go,
},
};
function printAuthorInfo(author: { id: number; name: string}) {
console.log(`${author.id}-${author.name}`);
}
|
cs |
그러면 이런식으로 나타나게 될것이다
그런데 이때 author 프로퍼티안에 age라는 프로퍼티를 추가하라는 수정사항이 생기면 Post 변수에도 추가를 해주어야 하며
함수에도 또 추가를 해주어야 한다.
그런데 이때 함수가 너무 많으면 하나씩 추가 해줘야 하는 번거로움이 생긴다.
이때 사용하면 좋은 것이 인덱스드 액세스 타입을 이용하면 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
//인덱스드 액세스 타입
interface Post {
title: string;
content: string;
author : {
id: number;
name: string;
};
}
const post: Post {
title: computer ko,
content: typescript,
author: {
id: 1,
name: go,
},
};
function printAuthorInfo(author: Post["author"]) {
console.log(`${author.id}-`${author.name});
}
|
cs |
이런식으로 Post 타입에 뽑아내고 싶은 프로퍼티의 타입을 써주면 된다.
그러면 author 객체만 가져올 수 있게 된다.
이렇게 되면 새로운 프로퍼티가 추가되더라도 별도로 함수에 수정이 필요하지 않게 된다.
또한 인덱스 타입은 연결해서 쓸 수 있는데 에를 들면 author의 id만 뽑아내고 싶다면
Post["author"]["id"] 이런식으로도 가능하다
주의해야할 점은
인덱스에 타입을 쓸 때 변수는 들어가면 안된다. 타입만 가능하다.
예를 들면 "author" 대신에 const key = "author" 후 Post[key]는 안된다는 뜻이다.
"author"는 스트링 리터럴 타입이라 가능, key는 값이기 때문에 안된다.
배열에서의 인덱스드 액세스 타입
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
//인덱스드 액세스 타입
type PostList = {
title: string;
content: string;
author : {
id: number;
name: string;
};
}[];
const post: PostList[number] {
title: computer ko,
content: typescript,
author: {
id: 1,
name: go,
},
};
function printAuthorInfo(author: PostList[number]["author"]) {
console.log(`${author.id}-`${author.name});
}
|
cs |
이렇게 타입의 배열이 있다고 하면
PostList[number] 이렇게 하면 PostList에서 하나의 Post를 뽑아낼 수 있게 된다.
끝
참고: 한 입 크기로 잘라먹는 타입스크립트 - 이정환
반응형
'언어 > 타입스크립트' 카테고리의 다른 글
타입스크립트 맵드 타입 - typescript mapped type (0) | 2025.02.17 |
---|