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