타입스크립트는 내가 정의한 타입을 필요에 따라 부분만 혹은 전부 가져다 쓰는 등 다양한 방법으로 변형시킬 수 있게 한다.
Partial<Type>
얘는 Type에 지정한 내용을 전부 가져다 쓸 수 있는데 옵셔널이다. 옵셔널로 쓸 수 있다는 말은 타입을 지정은 해주되 일부분의 데이터만 리턴되어도 상관이 없다는 뜻이다.
interface Todo {
title: string;
description: string;
}
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate };
}
const todo1 = {
title: "organize desk",
description: "clear clutter",
};
const todo2 = updateTodo(todo1, {
description: "throw out trash",
});
Required<Type>
Partial과 반대로 타입에 명시된 모든 속성을 충족시켜야 한다.
interface Props {
a?: number;
b?: string;
}
const obj: Props = { a: 5 };
const obj2: Required<Props> = { a: 5 };
Readonly<Type>
한번 지정된 데이터를 나중에라도 수정하고 싶을 때 수정이 불가함.
interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: "Delete inactive users",
};
todo.title = "Hello";
Cannot assign to 'title' because it is a read-only property.
Record<Keys, Type>
앞에는 키값이 뒤에는 타입이 들어오는 형태의 오브젝트 타입임. 속성값을 나타내는 타입을 다른 타입이랑 매칭시킬 때 쓰임.
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
cats.boris;
//const cats: Record<CatName, CatInfo>
Pick<Type, Keys>
이미 만들어진 타입에서 일부만 가져다 쓸 때 사용. 두 개의 타입에서 필요한 부분만 빼서 합칠 수도 있음.
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
//const todo: TodoPreview
참고: https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys
'맨땅에 헤딩하기 > 개발공부' 카테고리의 다른 글
[ESLint disable] 검열을 거두어주십쇼 (0) | 2023.12.27 |
---|---|
[개발일기] Static HTML과 Implicit ARIA role (1) | 2023.10.07 |
[git] 문제의 시초를 잡는 조력자 git bisect (0) | 2023.08.13 |
[JavaScript] generator 와 yield 정리 (0) | 2022.04.15 |
[git] Rebase 정리 (0) | 2022.04.14 |