Skip to content

튜플 (Tuple)

TypeScript에서 튜플은 고정된 길이와 각 요소별 타입이 정해진 배열을 말한다.
일반 배열은 요소 개수와 타입이 유연하지만, 튜플은 정해진 순서와 타입을 따라야 한다.
실행 시에는 일반 배열로 동작하지만, 개발 시점에서만 타입 체크가 일어난다.


1. 기본 문법

튜플은 요소의 타입과 순서를 명시하여 정의한다.

ts
let myTuple: [string, number, boolean];

2. 초기화

튜플을 초기화할 때는 정의한 순서와 타입에 맞는 값을 할당해야 한다.

ts
let myTuple: [string, number, boolean];

myTuple = ["Hello", 30, true];
myTuple = ["Hello", false, 100]; // 오류: 타입 불일치
myTuple = ["Hello", 100]; // 오류: 요소 개수 불일치

3. 요소 접근 및 변경

튜플의 요소는 인덱스를 사용해 접근하고 변경할 수 있으며, 타입을 지켜야 한다.

ts
let exampleTuple: [string, number];
exampleTuple = ["hello", 42];

console.log(exampleTuple[0]); // "hello"
console.log(exampleTuple[1]); // 42

exampleTuple[0] = "world";
exampleTuple[1] = 100;
exampleTuple[0] = 100; // 오류

4. 구조 분해 할당

튜플은 구조 분해 할당을 통해 각 요소를 변수로 뽑아낼 수 있다.

ts
let getUserInfo: [number, string] = [1, "Jerry"];

let [id, name] = getUserInfo;

ts
function getUserInfo(): [number, string] {
  return [1, "Jerry"];
}

const [userid, username] = getUserInfo();

5. 타입 별칭과 활용

튜플에 의미 있는 이름을 붙여서 재사용할 수 있다.

ts
type Flavor = string;
type Price = number;

type IceCream = [Flavor, Price];

const Vanilla: IceCream = ["Vanilla", 1000];

Vanilla[0]; // 문자열 타입
Vanilla[1]; // 넘버 타입

6. 배열 안의 튜플

튜플을 요소로 가지는 배열도 만들 수 있다.
예를 들어, 위도와 경도를 담은 튜플을 배열로 관리하면 좌표 리스트를 표현할 수 있다.

ts
type Lat = number; // 위도
type Lng = number; // 경도

type Coord = [Lat, Lng];

let coords: Coord[] = []; // 빈 배열로 초기화

coords.push([36, -99]);
coords.push([true, "7"]); // 오류: 타입 불일치
  • Coord는 항상 [number, number] 형태여야 한다.
  • 따라서 coords 배열은 [number, number] 형태의 튜플만 담을 수 있다.
  • 좌표값처럼 쌍 데이터가 반복되는 경우에 유용하다.

7. 반복문

ts
type Lat = number;
type Lng = number;
type Coord = [Lat, Lng];

let coords: Coord[] = [];

coords.push([36, -99]);
coords.push([40, -74]);

// for...of 반복문에서 구조 분해 할당
for (const [lat, lng] of coords) {
  console.log(`위도: ${lat}, 경도: ${lng}`);
}
  • for of문에서 [lat, lng] 구조 분해 할당을 사용하면 직관적으로 위도/경도를 다룰 수 있다.

ts
coords.forEach(([lat, lng]) => {
  console.log(`(${lat}, ${lng})`);
});
  • 일반 배열과 동일하게 forEach, map 등 고차 함수에서도 활용 가능하다.

💡 튜플은 데이터 구조의 일관성을 보장하기 때문에, 반복문과 함께 쓰면 안전하게 다룰 수 있다.



```