
⇒ 인덱스를 이용해서 다른 타입내에 특정 프로퍼티의 타입을 추출하는 타입
interface Post {
title: string;
content: string;
author: {
id: number;
name: string;
age: number;
};
}
function printAuthorInfo1(author: { id: number; name: string }) {
console.log(`${author.name}-${author.id}`);
}
function printAuthorInfo2(author: { id: number; name: string }) {
console.log(`${author.name}-${author.id}`);
}
function printAuthorInfo3(author: { id: number; name: string }) {
console.log(`${author.name}-${author.id}`);
}
const post: Post = {
title: "게시글 제목",
content: "게시글 본문",
author: {
id: 1,
name: "제노",
age: 27,
},
};
문법
function printAuthorInfo(author: Post["author"]) {
console.log(`${author.name}-${author.id}`);
}
⇒ ex) id 프로퍼티의 타입만 가져오는 방법
type PostList = {
title: string;
content: string;
author: {
id: number;
name: string;
age: number;
};
}[];
// 타입명[타입]["프로퍼티"]
function printAuthorInfo2(author: Post["author"]["id"]) {
console.log(`${author.name}-${author.id}`);
}
⇒ 타입명[타입]
const post2: PostList[number] = {
title: "게시글 제목",
content: "게시글 본문",
author: {
id: 1,
name: "제노",
age: 27,
},
};
type Tup = [number, string, boolean];
type Tup0 = Tup[0];
type Tup1 = Tup[1];
type Tup2 = Tup[2];
interface Person {
name: string;
age: number;
}
function getPropertyKey(person: Person, key: "name" | "age") {
return person[key];
}
keyof 타입명
.
.
function getPropertyKey(person: Person, key: keyof Person) {
return person[key];
}
keyof typeof 변수
.
.
type Person2 = typeof person;
function getPropertyKey2(person: Person, key: keyof typeof person) {
return person[key];
}
⇒ interface에서는 만들 수 없다. type 별칭 사용!
type PartialUser = {
[key in "id" | "name" | "age"]: User[key];
};
.
.
function updateUser(user: User) {
// ... 수정하는 기능
}
updateUser({
age: 25,
});
[key in "id" | "name" | "age"]?: User[key];
type BooleanUser = {
[key in "id" | "name" | "age"]: boolean;
// [key in keyof User]: boolean
};
type ReadonlyUser = {
readonly [key in keyof User]: User[key];
};
type Color = "red" | "black" | "green";
type Animal = "dog" | "cat" | "chicken";
type ColoredAnimal = "red-dog" | "red-cat" | "red-chicken" | "black-dog";
type ColoredAnimal2 = `${Color}-${Animal}`;