Skip to content
tsCheatSheet
GitHub

Tuples

Typed arrays.

Define Tuple

let aTuple: [number, boolean, string];

// initialize correctly
aTuple = [3, true, 'Hello World!'];

// initialize incorrectly; throws an error;
// order of types must match
aTuple = [true, 'Hello Wold!', 3];

Readonly Tuple

// We have no type safety in our  previous tuple for
// array indices 3+
aTuple.push('added after initialization');
console.log(aTuple); // works because it isn't readonly

// define readonly tuple
const aReadonlyTuple: readonly [number, boolean, string] = [
	3,
	true,
	'Hello World!',
];

aReadonlyTuple.push('added after initialization');
// throws error as it is readonly.

Named Tuples

Named tuples give us better context.

const graph: [x: number, y: number] = [51.0, 49.0];

Destructuring Tuples

Tuples are arrays and they can be destructured as such.

const graph2: [number, number] = [51.0, 49.0];
const [x, y] = graph;