TypeScript Snippet Cheatsheet
Overview
섹션 제목: “Overview”TypeScript에서 자주 다시 찾게 되는 병렬 처리, 기본 연산자, Map, 데이터 변환 예제를 짧게 모아둔 문서다.
Common Snippets
섹션 제목: “Common Snippets”1) Promise.all()로 병렬 처리
섹션 제목: “1) Promise.all()로 병렬 처리”- 목적: 서로 의존하지 않는 비동기 작업을 동시에 실행
- 예제:
const [users, posts, comments] = await Promise.all([ fetchUsers(), fetchPosts(), fetchComments(),]);- 메모:
- 전체 실행 시간은 보통 가장 오래 걸리는 Promise 시간에 가깝다.
- 하나라도
reject되면 전체가 실패하므로try/catch로 감싸는 편이 안전하다.
2) ?? 와 || 구분
섹션 제목: “2) ?? 와 || 구분”- 목적: 기본값 처리 시
null/undefined만 비어 있는 값으로 볼지, falsy 전체를 볼지 구분 - 예제:
const a = input ?? 'default';const b = input || 'default';- 메모:
??: 왼쪽 값이null또는undefined일 때만 오른쪽 값을 쓴다.||: 왼쪽 값이false,0,'',NaN,null,undefined중 하나면 오른쪽 값을 쓴다.
3) Map 생성과 기본 사용
섹션 제목: “3) Map 생성과 기본 사용”- 목적: 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로 다시
4) Map 순회
섹션 제목: “4) Map 순회”- 목적: 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)감각으로 쓰면 헷갈릴 수 있다.
5) Map -> Array
섹션 제목: “5) Map -> Array”- 목적:
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()과 전개 연산자(...) 둘 다 자주 쓴다.
6) Set -> Array
섹션 제목: “6) Set -> Array”- 목적:
Set을 일반 배열로 바꾸기 - 예제:
const companies = new Set<string>().add('apple').add('google').add('ms');
const arr1 = Array.from(companies);const arr2 = [...companies];7) Array -> Map, Set
섹션 제목: “7) Array -> Map, Set”- 목적: 배열을 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);