DEV Community

Hajar | هاجر
Hajar | هاجر

Posted on

Tuple Types in Typescript

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
Enter fullscreen mode Exit fullscreen mode

Naming & Destructuring Tuples

To enhance code readability, you could name the Tuple type elements.

let turtle: [name: string, age: number] = ["Zanjabeel", 14];
Enter fullscreen mode Exit fullscreen mode

Or you could also destructure it.

const turtle: [string, number] = ["Zanjabeel", 14];
const [name, age] = turtle;
Enter fullscreen mode Exit fullscreen mode

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]'.
Enter fullscreen mode Exit fullscreen mode

This feature is particularly valuable when you want to ensure the immutability of certain data structures.

Thanks for reading.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay