콘텐츠로 이동

TypeScript Snippet Cheatsheet

등록일

수정일

TypeScript에서 자주 다시 찾게 되는 병렬 처리, 기본 연산자, Map, 데이터 변환 예제를 짧게 모아둔 문서다.

  • 목적: 서로 의존하지 않는 비동기 작업을 동시에 실행
  • 예제:
const [users, posts, comments] = await Promise.all([
fetchUsers(),
fetchPosts(),
fetchComments(),
]);
  • 메모:
    • 전체 실행 시간은 보통 가장 오래 걸리는 Promise 시간에 가깝다.
    • 하나라도 reject 되면 전체가 실패하므로 try/catch로 감싸는 편이 안전하다.
  • 목적: 기본값 처리 시 null/undefined만 비어 있는 값으로 볼지, falsy 전체를 볼지 구분
  • 예제:
const a = input ?? 'default';
const b = input || 'default';
  • 메모:
    • ??: 왼쪽 값이 null 또는 undefined일 때만 오른쪽 값을 쓴다.
    • ||: 왼쪽 값이 false, 0, '', NaN, null, undefined 중 하나면 오른쪽 값을 쓴다.
  • 목적: key 기반 데이터 저장, 수정, 조회
  • 예제:
const userRoles = new Map<string, string[]>();
userRoles.set('admin', ['read', 'write']);
userRoles.set('guest', ['read']);
const adminRoles = userRoles.get('admin');
const hasGuest = userRoles.has('guest');
userRoles.delete('guest');
  • 메모:
    • 같은 key로 다시 set() 하면 기존 값이 덮어써진다.
    • get()은 데이터가 없으면 undefined를 반환한다.
  • 목적: key와 value를 함께 순회
  • 예제:
for (const [key, value] of userRoles) {
console.log(key, value);
}
userRoles.forEach((value, key) => {
console.log(key, value);
});
  • 메모:
    • forEach()(value, key) 순서라서 배열의 (item, index) 감각으로 쓰면 헷갈릴 수 있다.
  • 목적: Map 데이터를 배열이나 객체 배열로 변환
  • 예제:
const osMap = new Map<string, string>()
.set('apple', 'ios')
.set('google', 'android')
.set('ms', 'windows');
const entries = Array.from(osMap);
const objects = Array.from(osMap, ([name, os]) => ({ name, os }));
const objects2 = [...osMap].map(([name, os]) => ({ name, os }));
  • 메모:
    • Array.from()과 전개 연산자(...) 둘 다 자주 쓴다.
  • 목적: Set을 일반 배열로 바꾸기
  • 예제:
const companies = new Set<string>().add('apple').add('google').add('ms');
const arr1 = Array.from(companies);
const arr2 = [...companies];
  • 목적: 배열을 key-value 구조 또는 중복 없는 컬렉션으로 변환
  • 예제:
const items = ['apple', 'google', 'ms'];
const map = new Map<string, number>(items.map((item, idx) => [item, idx]));
const set = new Set<string>(items);