TypeScript Tuples


Fixed-Type Collections

A tuple is a compact data grouping where each slot carries a defined data type and a set size.

This format is helpful because every slot has a precise value classification.

Illustration:

let dataBundle: [number, boolean, string];  
dataBundle = [42, true, 'Engineer Mode']; 

Changing the position of elements will result in a type issue.


Incorrect Setup:

let dataBundle: [number, boolean, string];  
dataBundle = [false, 'Mismatch Detected', 42]; 

Immutable Structure

One clever habit is locking your tuple to make it unchangeable.

Type assurance applies only to the originally defined segments.

Example:

let record: [number, boolean, string]; 
record = [99, false, 'Immutable Check']; 

Record.push('Unexpected Entry'); 
console.log(record); 

Although the first three elements were type-checked, extra additions bypass enforcement.


Frozen Tuples

Protect your structure from modifications using the readonly marker.

Sample:

const secureTuple: readonly [number, boolean, string] = [81, true, 'Final Form']; 
 secureTuple.push('Unauthorized Access'); 

React Tuple Example

React's useState returns a familiar dual-structure — first, the value; second, the updater.

Familiar Pattern:

const [theme, setTheme] = useState('Dark'); 

Here, the first element is a string, and the second is a mutator function.


Labeled Tuples

Assigning names to tuple positions brings clarity and enhances readability.

const coordinates: [lat: number, lng: number] = [12.34, 56.78]; 

Here, lat and lng indicate the nature of each number.


Pulling Apart Tuples

You can dismantle a tuple easily using destructuring syntax.

Usage:

const angle: [number, number] = [45, 90]; 
Const [start, end] = angle; 

The values are unpacked into standalone variables with meaningful names.


Prefer Learning by Watching?

Watch these YouTube tutorials to understand TYPESCRIPT Tutorial visually:

What You'll Learn:
  • 📌 Tuples - TypeScript Programming Tutorial #6
  • 📌 TypeScript Tutorial #20 - Tuples
Previous Next