특정 타입의 부분 집합을 만족하는 타입을 정의.
어떤 타입의 부분만 있어도 됨. 비어있어도 ok. 공집합도 부분집합의 일부
interface Address {
email: string;
address: string;
}
const me: Partial<Address> = {};
const you: Partial<Address> = {email: 'abc@gmail.com'};
const all: Partial<Address> = {email: 'abc@gmail.com', address: 'asfasd'};
//위 코드와 동일
// const all: Address = {email: 'abc@gmail.com', address: 'asfasd'};
어떤 타입에서 특정 속성만 선택해서 타입 정의하는데 사용
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
const todo: Pick<Todo, 'title' | 'completed'> = {
title: 'clean room',
completed: true
}
어떤 타입에서 특정 속성만 제거해서 타입 정의하는데 사용
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
const todo2: Omit<Todo, 'description'> = {
title: 'clean room',
completed: true,
createdAt: 124532
}
어떤 타입이 일부 속성을 선택사항으로 정의했을 때도 객체에 Required 형식으로 타입을 지정하면 해당 타입의 모든 속성이 포함되어 있는지를 확인한다.
type User = {
firstName: string;
lastName?: string;
//lastName 속성은 선택사항으로 객체 생성시 없어도 오류 발생하지 않음
}
let firstUser: User = {
firstName : 'John'
}
//User 타입의 속성이 선택사항으로 설정되어 있더라도 관계없이 모든 속성에 대해 확인
let secondUser: Required<User> = {
firstName : 'John',
lastName : 'Doe'
//만약 lastName 없으면 오류 발생
}
Record<keys, Type>
속성 키가 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" }
}
type T0 = ReturnType<() => string> //string
type T1 = ReturnType<(s: string) => void> //void
function fn(str: string) {
return str
}
const a: ReturnType<typeof fn> = 'Hello';
const b: ReturnType<typeof fn> = true; //ERROR!
ReturnType<typeof fn>
= ReturnType<(str: string) => string>
= string
➡️ 결국 const b: ReturnType<typeof fn>
= const b: string = true
true
는 boolean형이기 때문에 오류 발생