Tewple or Tupple? Well both actually, keep this in mind during discussions.
Table of contents
📚 What is a Tuple
🧬 Usage
☠ The "tread with caution"
📚 What is a Tuple
Okay, so what is a Tuple? Simply put, it's a data structure, that consists of a fixed length array where each item may or may not be of the same type.
// Using a type
type MyTupleType = [boolean, string];
// Using an interface
interface MyTupleInterface
{
0: boolean
1: string,
};
The above definitions are identical and lets us choose which is best for our situation.
🧬 Usage
Using our definitions above, let's create our first Tuple!
const myTuple: MyTupleType = [false, "stringValue"]
Great, so what can we do with our Tuple?
// Accessing our data
const myBoolean = myTuple[0]
const myString = myTuple[1]
const [myBoolean, myString] = myTuple;
// Setting our data
myTuple[0] = true;
myTuple[1] = "Another String";
// Looping our data... remember, it's an Array.
myTuple.forEach(m => console.log(m));
// Useful for functions, this pattern is widely used with React Hooks
function validate(value: any): MyTupleType {
// Some validation here
return [false, "Invalid value provided"]
}
☠ The "tread with caution"
Because a Tuple is an array, we're allowed to push in new data 👀.
// Continuing from above
myTuple.push(true, "why is this possible");
myTuple.push("why is this possible", true);
Both the cases above are valid, as the compiler is unioning our types. In our example this produces the type of string | boolean
.
This may not immediately come across as a bad thing, however try accessing any of your newly pushed data and experience the wrath of the compiler!
const [a1, a2, b1, b2] = myTuple;
// const b2: undefined
// Tuple type 'MyTupleType' of length '2' has no element at index '2'.
const myValue = myTuple[3];
// Tuple type 'MyTupleType' of length '2' has no element at index '3'
Proof read & edited by my beautiful wife ❤!
Remember to #KeepHavingFun
Top comments (0)