배열과 튜플

Typescript 언어

Arrays in Typescript

Typed Arrays : 원소들이 동일한 타입의 값인 것

annotation 없어도 존재하는 원소들을 보고 inference 한다.

빈 배열은 inference할 수 없으므로 any타입이 된다.

1
2
3
4
5
6
7
8
// type annotation
const carMarkers: string[] = ['ford', 'toyota', 'chevy'];

// Date[] 타입으로 inference
const dates = [new Date(), new Date()];

// 2차원. string[][] type이다.
const carsByMake = [['f150'], ['corolla'], ['camaro']];

특징

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 배열에서 추출시 type inference 한다.
const car = carMakers[0]; // string type
const myCar = carMakers.pop(); // string type

// 배열에 동일하지 않은 type의 값은 추가할 수 없다.
carMakers.push(100); // string[]에 number를 넣으면 오류 발생

// 'map, 'forEach', 'reduce' 사용
carMakers.map((car: string): string => {
  return car.toUpeerCase();
});

// 다수의 type 사용.
// const importantDates: (string | Date)[]로 inference 된다.
const importantDates = [new Date(), '2030-10-10'];
// annotation
const importanteDates: (Date | string)[] = [new Date()];

Tuple

각 원소가 기록의 속성을 나타내는 배열과 같은 구조

‘drink’를 나타내는 object의 color는 brown, carbonated는 true, sugar는 40이다.

이를 [brown, true, 40]이라는 tuple로 나타내는 것.

첫번째 원소가 ‘color`를 나타내는 string, 두번째가 carbonation를 나타내는 boolean, 세번째가 sugar를 나타내는 number라는 것을 저장해둔다. 순서는 고정된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const drink = {
  color: 'brown',
  carbonated: true,
  sugar: 40,
};

// inference되지만, annotation으로 표시할 수 있다.
const pepsi: [string, boolean, number] = ['brown', true, 40];

// tuple type을 설정하여 여러번 일관되게 적용할 수 있다.
type Drink = [string, boolean, number];
const sprite: Drink = ['clear', true, 40];
const tea: Drink = ['brown', false, 0];

// type은 알지만 무엇을 의미하는 숫자인 지 알 수 없다.
const carSpecs: [number, number] = [400, 3354];

// 튜플은 number의 의미를 알 수 있음.
const carStats = {
  horsepower: 400,
  weight: 3354,
};