본문 바로가기

개발/TS

[TS] TS Doc Reference 1회독

Utility Types

타입스크립트에서 제공되는 유틸리티 타입은 타입 변형 기능을 제공해 줍니다.

 

Awaited<Type>

: async 함수 내부 await 같은 연산 또는 Promise의 .then() 함수를 모델링하는 것 의미합니다.

 

Promise를 재귀적으로 풀어내는 방식(recursively unwrap)에 초점이 있습니다.

recursively unwrap은 기존 Promise 타입을 Awaited로 감싸면 Promise 타입을 풀어서 최종 결과 타입을 가져온다는 의미입니다.
type p = Promise<string>; // Promise<string>
type A = Awaited<Promise<string>>; // string
type B = Awaited<Promise<Promise<number>>>; // number
type C = Awaited<boolean | Promise<number>>; // number | boolean

 

Partial<Type>

단어의 의미처럼 일부를 의미하는데 type이나 interface의 일부 또는 전체 속성을 다 포함하는 것을 의미합니다. Partial에 사용된 타입의 부분집합이 모두 사용가능하다는 의미입니다.

type T1 = {a: string; b: number;}
interface T2 = {c: boolean; d: string;}

function t(v1: Partial<T1>, v2: Partial<T2>) {
  return {...v1, ...v2};
}

test({a: ''}, {c: true, d: ''}); // possible
test({b: 1}, {c: true}); // possible
test({a: '', b: 2}, {d: ''}); // possible

 

Required<Type>

Partial의 반대로 type이나 interface에서 옵셔널로 되어있던 속성 즉 해당 타입 내 모든 속성이 필요하도록 변경합니다.

interface T1 = {c?: boolean; d?: string;}

const t1: T1 = {c: true}; // Ok
const t2: Required<T1> = {d: ''}; // error: property 'c' is missing

 

Readonly<Type>

타입 내 모든 속성을 readonly로 변경하는 유틸리티 타입입니다. 해당 타입은 Object.freeze 함수를 사용할 때 유용합니다.

interface T1 { a: string; }

const t1: Readonly<T1> = { a: '' };
t1.a = 'nulzi'; // error: cannot assign

 

Record<Keys, Type>

해당 타입은 키와 그에 해당하는 값이 다른 type이나 interface로 존재할 때 유용합니다.

type Keys = 'k1' | 'k2' | 'k3';
interface Val = {
  v1: number;
  v2: string;
}

const obj: Record<Keys, Val> = {
  k1: { v1: 1, v2: '1'},
  k2: { v1: 2, v2: '2'},
  k3: { v1: 3, v2: '3'}
};

 

참고

https://www.typescriptlang.org/docs/handbook/utility-types.html

'개발 > TS' 카테고리의 다른 글

[TS] TS Doc Reference 1회독 - 2  (1) 2025.07.18
[TS] TS Doc Handbook 1회독 - 10  (0) 2025.07.03
[TS] TS Doc Handbook 1회독 - 9  (0) 2025.06.24
[TS] TS Doc Handbook 1회독 - 8  (0) 2025.06.20
[TS] TS Doc Handbook 1회독 - 7  (0) 2025.06.17