기본 타입이나 별칭 또는 인터페이스로 만든 원래 존재하던 타입들을 상황에 따라 유동적으로 다른 타입으로 변환하는 타입스크립트의 강력하고도 독특한 기능이다.
제네릭도 타입 조작하기 중 하나인데 내용이 방대해 따로 본 것
객체,배열 타입으로부터 특정 프로퍼티 타입을 쏙 뽑아 정의해주는 문법
interface Post {
title: string;
content: string;
author: {
id: number;
name: string;
};
}
const post: Post = {
title: "제목",
content: "게시글 본문",
author: {
id: 1,
name: "Kang",
},
};
function printAuthorInfo(author: { id: number; name: string }) {
console.log(`${author.name}-${author.id}`);
}
interface Post {
title: string;
content: string;
author: {
id: number;
name: string;
phone: number;
location: string;
};
}
const post: Post = {
title: "제목",
content: "게시글 본문",
author: {
id: 1,
name: "Kang",
phone: 01012341234;
location: "Korea";
},
};
function printAuthorInfo(author: { id: number; name: string phone: number; location: string }) {
console.log(`${author.name}-${author.id}`);
}
function printAuthorInfo2(author: { id: number; name: string phone: number; location: string }) {
console.log(`${author.name}-${author.id}`);
}
function printAuthorInfo3(author: { id: number; name: string phone: number; location: string }) {
console.log(`${author.name}-${author.id}`);
}
printAuthorInfo(post.author)
인덱스드 엑세스 타입
이다.
printAuthorInfo
의 타입을Post[”author"]
로 정의해준다.
Post[”author"]
에 “author”는 변수나 값이 아니라타입
이다.const key = ‘author’ function printAuthorInfo(author: Post[key])
와 같이 작성하면 에러가 발생한다!
Post[”author”][”id”]
라고 작성하면 author 에 id만 가져올 수 있다!
type PostList = {
title: string;
content: string;
author: {
id: number;
name: string;
};
}[];
function printAuthorInfo(author: PostList[number]["author"]) {
console.log(`${author.name}-${author.id}`);
}
const post: PostList[number] = {
title: "제목",
content: "게시글 본문",
author: {
id: 1,
name: "Kang",
},
};
printAuthorInfo(post.author);
그리고 post를 보자 . PostList[number]
? 대괄호에 number라니..?
이렇게 쓰면 문제 없이 된다.. 더 신기한 건 PostList[0]
과 같이 어떤 숫자를 넣어도 정상적으로 동작한다는 점.
function printAuthorInfo(author: PostList[number]["author"])
에서도 매개변수의 타입을 [number] 이후 [”author”] 를 지정해줌을 알 수 있다.
튜플의 인덱스드 액세스는 별 거 없다.
//튜플 인덱스드 엑세스 타입
type Tup = [number, string, boolean]
type Tup0 = Tup[0];
type Tup1 = Tup[1];
type Tup2 = Tup[2];
//최적의 공통타입 추출
type TupNum = Tup[number];