타입 조작하기
인덱스트 엑세스 타입
type PostList = {
title: string;
content: string;
author: {
id: number;
name: string;
age: number;
location: string;
};
}[];
function printAuthorInfo(author: PostList[number]["author"]) {
console.log(`${author.name} - ${author.id}`);
}
const post: PostList[number] = {
title: "게시글 제목",
content: "게시글 본문",
author: {
id: 1,
name: "이정환",
age: 27,
location: "South Korea",
},
};
printAuthorInfo(post.author);
type Tup = [number, string, boolean];
type Tup0 = Tup[0];
type Tup1 = Tup[1];
type Tup2 = Tup[2];
type TupNum = Tup[number];
keyof 연산자
type Person = typeof person;
function getPropertyKey(person: Person, key: keyof typeof person) {
return person[key];
}
const person = {
name: "이정환",
age: 27,
};
getPropertyKey(person, "name");
맵드 타입
interface User {
id: number;
name: string;
age: number;
}
type PartialUser = {
[key in "id" | "name" | "age"]?: User[key];
};
type BooleanUser = {
[key in keyof User]: boolean;
};
type ReadonlyUser = {
readonly [key in keyof User]: User[key];
};
function fetchUser(): User {
return {
id: 1,
name: "Rachel",
age: 25,
};
}
function updateUser(user: PartialUser) {
}
updateUser({
id: 1,
name: "Rachel",
age: 24,
});
템플릿 리터럴 타입
type Color = "red" | "black" | "green";
type Animal = "dog" | "cat" | "chicken";
type ColoredAnimal = `${Color}-${Animal}`;
const coloredAnimal: ColoredAnimal = "red-cat";
[참고]
한 입 크기로 잘라먹는 타입스크립트
- Section 8. 타입 조작하기 강의를 듣고 정리한 내용입니다.