[typescript] 튜플을 배열로 변환하고 정렬하기

TypeScript에서는 튜플을 배열로 변환하고 정렬하는 방법을 알아보겠습니다.

튜플을 배열로 변환하기

튜플을 배열로 변환하려면 spread operator를 사용하여 간단하게 변환할 수 있습니다. 예를 들어, 다음과 같이 작성할 수 있습니다.

const tuple: [number, string, boolean] = [1, "hello", true];
const array: Array<any> = [...tuple];
console.log(array); // [1, "hello", true]

배열 정렬하기

배열을 정렬하려면 Array 객체의 sort 메서드를 사용합니다. 숫자 배열의 경우 기본적으로는 오름차순으로 정렬됩니다. 문자열 배열의 경우 기본적으로는 사전순으로 정렬됩니다.

const numbers: number[] = [3, 1, 2, 5, 4];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 3, 4, 5]

const words: string[] = ["apple", "banana", "cherry"];
words.sort();
console.log(words); // ["apple", "banana", "cherry"]

요약

이제 TypeScript에서 튜플을 배열로 변환하고 정렬하는 방법을 알아보았습니다.

더 많은 정보는 TypeScript 공식 문서를 참조하세요.