You might have heard of tuples in the context of Python programming. Yes, Python has tuples built right into the language.
But don’t worry, you don’t need to know Python to understand tuples in TypeScript.
A tuple is a special type in TypeScript that represents an array with a fixed number of elements, where each element can have a different type.
Unlike regular arrays where all elements are usually of the same type — tuples allow you to define a specific type for each position in the array. This makes them perfect for representing structured and predictable data.
Think of a tuple as a mini-array where TypeScript knows the exact number of items and the exact type of each one in order.
Let's learn about how we will be using them
let chaiAurTuple: [string, number] = ["hey", 52];
console.log(chaiAurTuple[0]);
console.log(chaiAurTuple[1]);
let chaiAurTuple : [string, number,boolean] = ["hey", 52, true];
const [first,second,three] = chaiAurTuple;
console.log(first);
console.log(second);
console.log(three);
One common point of confusion is how TypeScript handles arrays that look like tuples but aren't explicitly typed as such. TypeScript is generally cautious and will infer a more flexible array type unless you tell it otherwise.
const movieInfo = ["welcome", "three idiots"];
const movieTuple: [string, string] = movieInfo;
There are two primary ways to tell TypeScript that you want a tuple:
function getMovieInfo(title: string): [string, number] {
return [title, title.length];
}
const [movieTitle, titleLength] = getMovieInfo("Inception");
as const Assertion: This is a shorthand that tells TypeScript to infer the most specific, immutable type possible. When used on an array literal, it creates a read only tuple.
const movieTuple = ["Forrest Gump", 1994] as const;
movieTuple[0] = "Singham";