Optional and Named Tuple Elements

Named Elements

You can give tuple positions names. The names only help readability and editor hints; access is still by index or destructuring.

Example

type Coordinates = [latitude: number, longitude: number];
type Range = [start: number, end: number, step?: number];

const hyderabad: Coordinates = [17.385, 78.4867];

function rangeToList([start, end, step = 1]: Range): number[] {
  const out: number[] = [];
  for (let i = start; i <= end; i += step) out.push(i);
  return out;
}

console.log("Lat/Lng:", hyderabad.join(", "));
console.log(rangeToList([1, 5]));
console.log(rangeToList([0, 10, 5]));

Output

Lat/Lng: 17.385, 78.4867
[ 1, 2, 3, 4, 5 ]
[ 0, 5, 10 ]

Readonly and Rest Elements

Example

A tuple can end with a rest element (...string[]), and readonly works on tuples too.

type LogLine = [level: "INFO" | "ERROR", message: string, ...tags: string[]];

const line1: LogLine = ["INFO", "Server started"];
const line2: LogLine = ["ERROR", "DB timeout", "db", "orders"];

const point: readonly [number, number] = [3, 4];
console.log(line1.length, line2.slice(2));
console.log(Math.hypot(point[0], point[1]));

Output

2 [ 'db', 'orders' ]
5

Practice

Exercise: Create a tuple type Student with named elements name (string), rollNo (number) and an optional section (string). Create two students, one without a section.

Show answer
type Student = [name: string, rollNo: number, section?: string];
const s1: Student = ["Kiran", 12, "B"];
const s2: Student = ["Divya", 7];
console.log(s1, s2);