Sometimes, you need to define arrays where the order and types of their elements should matter. In a case like that, Tuple types come in very handy.
For example, if you have a turtle = ["Zanjabeel", 14];
where Zanjabeel is its name, and 14 is its age. Declaring turtle
that way (without Tuple) will implicitly give it the type of (number|string)[]
(array of string
or number
), which will not help prevent someone from giving turtle
a non-string name or a not-a-number age.
Defining turtle
with Tuples
To guarantee that turtle
will have the first element as string
and the second one as number
, you’ll need to define it as a Tuple of length two.
let turtle: [string, number] = ["Zanjabeel", 14];
turtle[1] = "15" // Error Type: ‘string’ is not assignable to type ‘number’.
turtle[0] = "Ginger" // works fine
turtle[1] = 15 // works fine
Naming & Destructuring Tuples
To enhance code readability, you could name the Tuple type elements.
let turtle: [name: string, age: number] = ["Zanjabeel", 14];
Or you could also destructure it.
const turtle: [string, number] = ["Zanjabeel", 14];
const [name, age] = turtle;
Readonly Tuples
To make your Tuple array read-only, you can use readonly
.
const KEYS: readonly [KEY_1: string, KEY_2: number] = ["secret_key", 40];
// The following lines will throw compile-time errors.
KEYS[0] = "new_secret_key"; // Error: Cannot assign to '0' because it is a read-only property.
KEYS.push("new_secret_key"); // Property 'push' does not exist on type 'readonly [KEY_1: string, KEY_2: number]'.
This feature is particularly valuable when you want to ensure the immutability of certain data structures.
Thanks for reading.
Top comments (0)