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; // 오류

🧩 읽기 전용 튜플

튜플은 기본적으로 값을 변경할 수 있지만, readonly를 사용하면 요소 변경을 막을 수 있다.

ts
let mutableUser: [number, string] = [1, 'Jerry'];

mutableUser[1] = 'Tom'; // 가능
ts
let readonlyUser: readonly [number, string] = [1, 'Jerry'];

readonlyUser[1] = 'Tom'; // Error

4. 구조 분해 할당

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

ts
let userInfo: [number, string] = [1, 'Jerry'];

let [id, name] = userInfo;

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

const [userId, userName] = getUserInfo();

튜플은 각 요소의 위치에 의미가 있는 데이터를 표현할 때 유용하다.
예를 들어 [number, string] 형태라면 첫 번째 값은 id, 두 번째 값은 이름처럼 정해진 역할을 가질 수 있다.


5. 타입 별칭과 활용

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

ts
type Flavor = string;
type Price = number;

type IceCream = [Flavor, Price];

const vanilla: IceCream = ['Vanilla', 1000];

vanilla[0]; // string 타입
vanilla[1]; // number 타입

6. 배열 안의 튜플

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

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

type Coord = [Lat, Lng];

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

coords.push([37.5665, 126.978]); // 서울
coords.push([35.1796, 129.0756]); // 부산
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([37.5665, 126.978]); // 서울
coords.push([35.1796, 129.0756]); // 부산

// 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 등 고차 함수에서도 활용 가능하다.

💡 튜플은 각 요소의 타입과 순서를 명확히 표현할 수 있기 때문에, 반복문과 함께 사용할 때도 데이터를 더 안전하게 다룰 수 있다.