개발/typescript
타입스크립트 타입 조작 - 인덱스드 엑세스
모그
2024. 1. 3. 17:30
인덱스드 엑세스 타입
인덱스를 이용해 다른 타입내의 특정 프로퍼티 타입을 추출한다.
객체,배열,튜플에 사용 가능
📌객체 프로퍼티의 타입 추출
interface Post {
title:string,
content:string,
author: {
id:number,
name:string
}
}
만약 여기에서 author 프로퍼티의 타입에 관심이 있다면
function printInfo(author: {id:number, name:string}){
console.log(`${author.id} - ${author.name}`)
}
printInfo 함수의 인자는 author 프로퍼티이고, id와 name의 타입을 직접 명시해주면 나중에 타입 프로퍼티가 추가or삭제or수정되었을 때 귀찮아진다.
뭐든 중복되는 코드는 피하는 것이 좋다.
function printInfo2(author:Post["author"]){
console.log(`${author.id} - ${author.name}`)
}
Post ["author"]
Post타입 으로부터 [프로퍼티] 의 타입을 추출한다.
여기서 [ 인덱스 ] 내부에는 타입만 들어갈 수 있고, 값(ex.변수)은 들어갈 수 없다.
+
interface Post {
title:string;
content: {
contentnumber:number,
contenttitle:string
};
author : {
id: number;
name: string;
}
}
function printinfor (content : Post["content"]){ //여기서 인수로 들어가는 프로퍼티는
console.log(`${content.contentnumber}-${content.contenttitle}`) // 함수 구현부에서 언급되어야함
}
✔️또 인덱스를 중첩해 조금 더 구체적인 프로퍼티에까지 접근할 수 있다.
function printInfo2(author:Post["author"]["name"]){
console.log(`글쓴이는 ${author}`)
}
📌배열 요소의 타입 추출
type PostList = {
title:string,
content:string,
author: {
id:number,
name:string
}
}[];
이런 객체로 이루어진 배열 타입이 있다고 가정했을 때
const post2:PostList= { // 오류
title:"제목",
content:"내용",
author: {
id:1,
name:"글쓴이"
}
}
const post2:PostList[number]= { // O
title:"제목",
content:"내용",
author: {
id:1,
name:"글쓴이"
}
}
이 때 [number]대신 [0], [1], [2] ... 등등 숫자를 넣어도 똑같다.
+만약 배열타입의 객체는 그대로 유지한 채 [number] 라는 인덱스드 엑세스 타입을 지운다면 오류메시지가 뜬다.
type List = [
{
id:number,
name:string
},
{
id:number,
name:string
skill:boolean
},
]
type Listone = List[0]["id"] //number
type Listtwo = List[1]["skill"] //boolean
이런 방식으로도 접근 가능하다.
📌튜플의 요소 타입 추출하기
type tup = [number, string, boolean]
type tup0 = tup[0] // number
type typ1 = tup[1] // string
type typ2 = tup[2] //boolean
type typ3 = tup[number] //number|string|boolean
강의에서는 자주 쓰이는 문법이라고 하는데 사실 굳이 이걸 쓰지 않더라도 코드 작성은 가능할 것 같다..
실제로 어떤 경우에 쓰이는지 아직 감이 안온다.