A tuple is a fixed-length TypeScript array whose positions have specified types. For example, [string, number] requires a product name first and a price second; access values with normal array indexes. section 9.3
Representing product data
let hat: [string, number] = ["Hat", 100]; let gloves: [string, number] = ["Gloves", 75]; writePrice(hat[0], hat[1]); writePrice(gloves[0], gloves[1]); The annotation matters: without it, TypeScript infers a variable-length array whose elements can be string or number, rather than a fixed pair. section 9.3
Tuples compile to ordinary JavaScript arrays, so standard array operations, destructuring, and iteration remain available. Iterating mixed positions requires a string | number annotation and a type guard. section 9.3.1
Use the tuple form that matches the structure you need:
- Store multiple tuple values with an array type such as [string, number][]. section 9.3.2
- Combine tuples with other alternatives in a union, then narrow arrays with instanceof Array and other values with typeof. section 9.3.2
- Add trailing optional positions with ?. An omitted value becomes undefined, so processing code must narrow it before use. section 9.3.3
- Add a rest element such as ...number[] for variable-length tuples, but recognize that this weakens the fixed structure that makes tuples useful. section 9.3.4
Optional tax rate
let hat: [string, number, number?] = ["Hat", 100]; let gloves: [string, number, number?] = ["Gloves", 75, 10]; let [name, price, taxRate] = gloves; if (taxRate != undefined) { price += price * (taxRate / 100); } Destructuring makes named local variables convenient, while the check prevents an omitted optional value from being used as a number. section 9.3.3
Listing 9.10 Using tuples in the index.ts file in the src folder
function calculateTax(amount: number): number {
return amount * 1.2;
}
function writePrice(product: string, price: number): void {
console.log(`Price for ${product}: $${price.toFixed(2)}`);
}
let hat: [string, number] = ["Hat", 100];
let gloves: [string, number] = ["Gloves", 75];
writePrice(hat[0], hat[1]);
writePrice(gloves[0], gloves[1]);
Inspect the complete product-price example, including tuple declarations, indexed access, and console output. section 9.3














