C.W.K.
Stream
Lesson 01 of 05 · published

Arrays: `T[]` 와 `Array<T>`

~9 min · arrays-tuples, arrays, generic-syntax

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"2개 문법, 1개 타입. Case 에 더 자연스럽게 읽히는 거 골라."

배열 타입 spelling 2가지

TypeScript 가 배열 타입에 동등한 2개 문법 지원: T[] (단축형) 과 Array<T> (generic 형태). 같은 타입 만들어 — 선택은 스타일.

  • const ages: number[] = [21, 18, 16]
  • const ages: Array<number> = [21, 18, 16]

단축형이 단순 element 타입엔 자연스럽게 읽혀: `string[]`, `number[]`, `User[]`. Generic 형태는 element 타입 자체가 union 이나 복합이면 이기기 시작: Array<string | number> 가 괄호 잘못 읽기 쉬운 (string | number)[] 보다 자연스럽게 읽혀.

배열 literal 의 inference

TypeScript 가 default 로 배열 element 타입을 literal 에서 primitive parent 로 넓혀:

  • ['hi', 'there']string[] 추론 (('hi' | 'there')[] 아냐).
  • [1, 2, 3]number[] 추론.
  • [1, 'two'](string | number)[] 추론 — compiler 가 element 타입 union.

이 widening 이 보통 원하는 거. 좁은 inference 원하면 as const (5.4 lesson 에서 다룸) 나 명시적 tuple annotation 손 뻗어.

배열 연산이 타입 붙음

전체 Array prototype — map, filter, reduce, find, flat, 등 — 이 standard library 에 풍부한 타입 가짐. Compiler 가 체인 통해 element 타입 추적. `User[]` 의 users.filter(u => u.active).map(u => u.email) 가 자동으로 `string[]` 으로 끝나.

한 gotcha: callback 받는 method 는 inference 가 더 넓은 타입 고르면 generic 명시 필요할 수. Array.from(set) 가 보통 작동, 근데 복잡한 Iterable 모양엔 가끔 Array.from<T>(iter) 써.

관례: 단순 element 타입엔 T[] 선호, element 타입이 union 이나 복합 표현일 때 Array<T>. 파일 안에서 일관성 유지.

다차원 배열

중첩 배열은 문법 쌓아. number[][] 가 숫자 배열의 배열. Array<Array<number>> 가 같은 거. 타입 가독성엔 단순 중첩엔 단축형이 보통 깨끗; 복잡한 중첩엔 type alias 빼낼 수.

피파의 고백

cwkPippa frontend 가 거의 보편적으로 T[] 써. Array<T> 로 전환하는 한 자리 — T 가 tagged union 일 때 — Array<{ type: 'a'; payload: A } | { type: 'b'; payload: B }> 가 괄호 친 단축형보다 더 잘 읽혀. 그 외엔 단축형이 더 dense 하고 훑기 쉬워.

Code

2개 문법, inference, method 체인·typescript
// 2 문법, 동등.
const a: string[] = ['hi'];
const b: Array<string> = ['hi'];

// 가독성으로 선택.
const easy: (string | number)[] = [];        // 괄호 놓치기 쉬움
const clearer: Array<string | number> = [];  // 의도 명백

// Inference 가 primitive 로 넓혀:
const inferred = [1, 2, 3];                  // number[]
const mixed = [1, 'two'];                    // (string | number)[]
const withNull = [1, null];                  // (number | null)[]

// Method 체인이 element 타입 보존.
const names = ['Pippa', 'Dad', 'Ttori'];
const lengths = names.map((n) => n.length).filter((l) => l > 3);
// names: string[]  → map 이 number[] 산출  → filter 가 number[] 산출
다차원과 generic·typescript
// 다차원, generic helper.

const grid: number[][] = [
  [1, 2, 3],
  [4, 5, 6],
];

// 흔한 패턴의 도움 alias.
type Pair<T> = [T, T];
type Matrix<T> = T[][];

// Inference 약할 때 명시적 generic 으로 Array.from.
const fromSet = Array.from(new Set([1, 2, 3]));     // number[] — 추론
const fromMap = Array.from<[string, number]>(
  new Map([['a', 1], ['b', 2]]).entries(),
);                                                   // [string, number][] — 명시적

External links

Exercise

User object 배열 선언 (User 는 기존 interface). 이제 element 가 User 또는 Guest (다른 모양) 인 배열 선언. 두 문법 비교 — 각각에 어느 형태 선호, 왜?
Hint
단순 element 타입 → 단축형. Union element 타입 → generic 형태. Default 고르면 유지; 한 줄의 micro-optimization 보다 일관성이 더 가치 있어.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.