튜플은 JavaScript에는 없는 TypeScript만의 고유한 타입입니다.
튜플은 길이와 순서, 타입이 고정되어 있는 배열입니다.
배열 대괄호 자체가 타입이 되고, 실제로 넣을 값에 맞게 대괄호 안에 길이와 순서를 맞춰 타입을 넣어줍니다. [타입]
// 숫자 값을 갖는 배열 타입
const color: number[] = [255, 0, 255]
const color: number[] = [255, 0, 255, 45]
// 숫자 값을 갖는 튜플 타입
const color: [number, number, number] = [255, 0, 255];
// 길이가 다름
// Type '[number, number, number, number]' is not assignable to type '[number, number, number]'.
// Source has 4 element(s) but target allows only 3.
const color: [number, number, number] = [255, 0, 255, 45];
타입에 사용할 수 있습니다.
type HTTPResponse = [number, string];
const goodRes: HTTPResponse = [200, "OK"];
튜플 생성 후에 추가 요소를 push나 pop하는 것을 막지 않습니다.
튜플은 백그라운드에서 실행되는 배열이여서 배열이 생성된 후 푸시를 사용하면 TypeScript가 오류를 표시하지 않습니다.
type HTTPResponse = [number, string];
const goodRes: HTTPResponse = [200, "OK"];
goodRes.push(123);
goodRes.pop();
튜플을 따르는 값을 가진 배열도 만들 수 있습니다.
type HTTPResponse = [number, string];
const responses: HTTPResponse[] = [
[404, "Not Found"],
[200, "OK"],
];