Utility Type

μ΄λ²ˆμ—” νƒ€μž…μŠ€ν¬λ¦½νŠΈμ—μ„œ μ œκ³΅ν•˜λŠ” μœ ν‹Έλ¦¬ν‹° νƒ€μž…λ“€ μ€‘μ—μ„œ 자주 μ‚¬μš©ν• λ§Œν•œ λͺ‡κ°€μ§€λ₯Ό κ³΅μ‹λ¬Έμ„œλ₯Ό 톡해 μ•Œμ•„λ³΄μž.

Awaited

μš°λ¦¬κ°€ 비동기 처리λ₯Ό ν•  λ•Œ μ‚¬μš©ν•˜λŠ” async await처럼 Promise객체의 λ¦¬ν„΄κ°’μ—λŒ€ν•΄ Promiseλ₯Ό λ²—κΈ΄ νƒ€μž…μ„ μ •μ˜ν• λ•Œ μ‚¬μš©λœλ‹€.


type UserPromise = Promise<{
  id: number;
  name: string;
}>;
type AwaitedUser = Awaited<UserPromise>;
async function User(): UserPromise {
  return { id: 1, name: "Awaited type example" };
}

async function PrintUser() {
  const user: AwaitedUser = await User();
  console.log(user);
}

PrintUser(); // { id: 1, name: 'Awaited type example' }

ReadOnly

type User = {
  name: string;
};

const user: User = {
  name: "this is user",
};
user.name = "Can I change property?";

console.log(user); // Can I change property?

// μœ„μ²˜λŸΌ 일반적으둜 μ •μ˜λœ 객체에 λŒ€ν•΄μ„œλŠ” ν”„λ‘œνΌν‹° 변경이 κ°€λŠ₯ν•˜λ‹€.

const user2: Readonly<User> = {
  name: "this is user",
};

// Cannot assign to 'name' because it is a read-only property.
user.name = "Can I change property?"; 

console.log(user);

ReadOnly ν‚€μ›Œλ“œλŠ” 말 κ·ΈλŒ€λ‘œ μ œλ„€λ¦­μœΌλ‘œ λ“€μ–΄μ˜¨ νƒ€μž…μ— λŒ€ν•΄ μ½κΈ°μ „μš©μœΌλ‘œ μ‚¬μš©ν•˜λ„λ‘ ν•΄μ£ΌλŠ” ν‚€μ›Œλ“œμ΄λ‹€.

ν•΄λ‹Ή νƒ€μž…μ„ μ‚¬μš©ν•˜λŠ” 객체의 ν”„λ‘œνΌν‹°κ°€ λ³€κ²½λ˜λŠ” 것을 μ›μΉ˜ μ•Šμ„λ•Œ μ‚¬μš©ν•œλ‹€.

Record


type Score = Record<string, number>;
const ExamScore: Score = { 
    math: 100,
    eng: 20,
    korean: 80
};

개인적으둜 자주 μ‚¬μš©ν•˜λŠ” ν‚€μ›Œλ“œμ΄λ‹€. μ œλ„€λ¦­μœΌλ‘œ 받은 keyκ°’κ³Ό valueκ°’μ˜ νƒ€μž…μ„ κ°€μ§„ 객체의 νƒ€μž…μ„ μ§€μ •ν• λ•Œ μ‚¬μš©λœλ‹€.

νŠΉμ΄ν•œ 점은 μ œλ„€λ¦­μœΌλ‘œ μ›μ‹œν˜• μžλ£Œν˜•μ€ λ¬Όλ‘ , λ¬Έμžμ—΄ λ¦¬ν„°λŸ΄μ„ μ‚¬μš©ν•  수 μžˆλ‹€.

type Subject = "math" | "eng" | "korean";
type Score = Record<Subject, number>;
const ExamScore: Score = {
    math: 100,
    eng: 20,
    korean: 80 
};

Pick

type Todo = {
  id: number;
  title: string;
  author: string;
  createdAt: string;
  isComplete: boolean;
};

const simpleTodo: Pick<Todo, "title" | "isComplete"> = {
  title: "Pick example!",
  isComplete: false,
};

기쑴에 μ‘΄μž¬ν•˜λ˜ νƒ€μž…μ˜ ν”„λ‘œνΌν‹° 쀑 λΆ€λΆ„μ μœΌλ‘œ μ§€μ •ν•˜μ—¬ λ”°λ‘œ νƒ€μž…μœΌλ‘œ μ‚¬μš©ν• μˆ˜ 있게 ν•΄μ€€λ‹€.

μƒˆλ‘œμš΄ νƒ€μž…μ„ μ •μ˜ν•˜ ν•„μš”μ—†μ΄ 기쑴에 μ‘΄μž¬ν•˜λ˜ νƒ€μž…μ„ μž¬μ‚¬μš©κ°€λŠ₯ν•˜λ‹€λŠ” μ μ—μ„œ μœ μš©ν•˜κ²Œ μ‚¬μš©μ΄ κ°€λŠ₯할것 κ°™λ‹€!

ReturnType

function Example(age: number) {
  return age + 1;
}

// Example ν•¨μˆ˜μ˜ 리턴값이 numberμ΄λ―€λ‘œ, ReturnType<typeof Example>은 number이닀.
const result: ReturnType<typeof Example> = Example(10);

ν‚€μ›Œλ“œ 이름 κ·ΈλŒ€λ‘œ ν•¨μˆ˜λ₯Ό μ œλ„€λ¦­μœΌλ‘œ λ°›μ•„ ν•΄λ‹Ή ν•¨μˆ˜μ˜ 리턴 κ°’μ˜ νƒ€μž…μ„ λ°˜ν™˜ν•΄μ€€λ‹€.

Last updated