Utility Type

Index Type

[]๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด index Type์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. computed property์ฒ˜๋Ÿผ ๊ณ„์‚ฐ๋œ ๊ฐ’์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

type Animal = {
  name: string;
  age: number;
  gender: 'male' | 'female';
};

type Name = Animal['name']; // string
const text: Name = 'hello';

Mapped Type

type์˜ key์— index type์„ ์‚ฌ์šฉํ•˜๋ฉด ์ „๋‹ฌ๋ฐ›์€ ํƒ€์ž…์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ํ•œ๋ฐ”ํ€ด ์ˆœํ™˜ํ•ฉ๋‹ˆ๋‹ค.

  • [P in keyof T]: ์ œ๋ ˆ๋ฆญ T์˜ ํ‚ค๋ฅผ ์ˆœํšŒ

  • T[P]: P๋ฅผ ํ‚ค๋กœ ํ•œ T์˜ value property

type Nullable<T> = { [P in keyof T]: T[P] | null };
const obj2: Nullable<Video> = {
  title: 'hi',
  author: null,
};

type Proxy<T> = {
  get(): T;
  set(value: T): void;
};

type Proxify<T> = {
  [P in keyof T]: Proxy<T[P]>;
};

Conditinal Type

์กฐ๊ฑด์„ ๋‹ฌ์•„์„œ ํƒ€์ž…์„ ์ง€์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 3ํ•ญ ์—ฐ์‚ฌ์ž ์‚ฌ์šฉ.

type Check<T> = T extends string ? boolean : number;
type Type = Check<string>; // boolean

ReadOnly

์ˆ˜์ •์ด ๋ถˆ๊ฐ€๋Šฅํ•œ ํƒ€์ž…์„ ๋งŒ๋“ฆ.

type ToDo = {
  title: string;
  description: string;
};

function display(todo: Readonly<ToDo>) {
  // todo.title = 'jaja';
}

Partial Type

์˜ต์…”๋„ ํ”„๋กœํผํ‹ฐ๋กœ ๋งŒ๋“ฆ

type ToDo = {
    title: string;
    description: string;
    label: string;
    priority: 'high' | 'low';
};

function updateTodo(todo: ToDo, fieldsToUpdate: Partial<ToDo>): ToDo {
    return { ...todo, ...fieldsToUpdate };
}

Pick Type

์ „๋‹ฌ๋ฐ›์€ ํƒ€์ž…์˜ ์ผ๋ถ€ ์š”์†Œ๋“ค๋งŒ ์‚ฌ์šฉ

type Video = {
    id: string;
    title: string;
    url: string;
    data: string;
};
type VideoMetadata = Pick<Video, 'id' | 'title'>;

function getVideoMetadata(id: string): VideoMetadata {
    return {
      id: id,
      title: 'title',
    };
}

Omit Type

pick type์˜ ๋ฐ˜๋Œ€๋กœ ์ผ๋ถ€ ์š”์†Œ๋ฅผ ์ œ์™ธํ•˜๊ณ  ์‚ฌ์šฉ

type Video = {
    id: string;
    title: string;
    url: string;
    data: string;
};
type VideoMetadata = Omit<Video, 'url' | 'data'>;

function getVideoMetadata(id: string): VideoMetadata {
    return {
      id: id,
      title: 'title',
    };
}

Record

์ฒซ ๋ฒˆ์งธ ์ œ๋„ค๋ฆญ์ด ํ‚ค, ๋‘ ๋ฒˆ์งธ ์ œ๋„ค๋ฆญ์ด ๋ฐธ๋ฅ˜๊ฐ€ ๋˜์–ด์„œ ์ƒˆ๋กœ์šด ํƒ€์ž…์„ ์กฐํ•ฉํ•จ.

type PageInfo = {
  title: string;
};
type Page = 'home' | 'about' | 'contact';

const nav: Record<Page, PageInfo> = {
  home: { title: 'Home' },
  about: { title: 'About' },
  contact: { title: 'Contact' },
};

Capitalize, Uppercase, Lowercase

ํƒ€์ž… ๊ฐ’๋“ค์˜ ์˜๋ฌธ๋ฒ• ํ‘œ๊ธฐ๋ฒ•์„ ๋ฐ”๊ฟ”์คŒ. ๋ฐฑ๋‹จ์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ํ†ต์ผ์„ฑ์—†์ด ์ฃผ๊ฑฐ๋‚˜ ํ•  ๋•Œ ๋งž์ถ”๊ธฐ์— ์šฉ์ดํ•จ.

Last updated

Was this helpful?