TypeScript의 유틸리티 타입 (2)

eeensu·2024년 1월 16일
0

typescript

목록 보기
19/22
post-thumbnail

Record<K,T>

객체의 타입을 생성하는데 사용된다. 주어진 키 K와 값의 타입 T를 가지는 객체의 타입을 생성한다.

const hexColorMap: Record<string, string> = {
    red: "FF0000",
    green: "00FF00",
    blue: "0000FF",
}
// 응용
type Fruit = 'apple' | 'banana' | 'orange';
type FruitPrices = Record<Fruit, number>;

const fruitPrices: FruitPrices = {
  apple: 1.5,
  banana: 0.75,
  orange: 2.0,
};
// 응용
type Students = "Sara" | "Kelly";

interface Grades {
    assign1: number,
    assign2: number,
}

const gradeData: Record<Students, Grades> = {
    Sara: { assign1: 85, assign2: 93 },
    Kelly: { assign1: 76, assign2: 15 },
};


Pick<T, K>

타입 T에서 일부 속성만 선택하여 새로운 타입을 생성한다.

interface Car {
  make: string;
  model: string;
  year: number;
  color: string;
}

type CarInfo = Pick<Car, 'make' | 'model'>;

const carInfo: CarInfo = {
  make: 'Toyota',
  model: 'Camry',
};


Omit<T,K>

타입 T에서 일부 속성을 제외하여 새로운 타입을 생성한다.

interface Book {
  title: string;
  author: string;
  pages: number;
  genre: string;
}

type BookSummary = Omit<Book, 'pages' | 'genre'>;

const bookSummary: BookSummary = {
  title: 'The Catcher in the Rye',
  author: 'J.D. Salinger',
};
profile
안녕하세요! 26살 프론트엔드 개발자입니다! (2024/03 ~)

0개의 댓글