Typescript tuple
Created By: chatGPT
TypeScript provides a very useful feature called tuples that allows you to store a fixed number of elements of various types. Tuples can help enforce type safety by ensuring that the values are read and written in the expected type and order. Here's how to declare and use a tuple in TypeScript.
let myTuple: [string, number];
myTuple = ['hello', 42];
In this example,
myTuple
is defined to hold a string followed by a number. If you try to assign values in a different order or different types, TypeScript will raise an error.myTuple = [42, 'hello']; // Error: Type 'number' is not assignable to type 'string'.
You can also access elements in a tuple just like you would with an array. To access the first element, you can use index 0, and for the second element, you use index 1.
console.log(myTuple[0]); // Outputs: 'hello'
console.log(myTuple[1]); // Outputs: 42
Tuples can also have optional elements. You can declare an element in the tuple as optional by adding a question mark
?
next to its type.let myOptionalTuple: [string, number?];
myOptionalTuple = ['hello']; // Valid
In the example above, the second element of
myOptionalTuple
can be omitted, making it flexible while maintaining type safety. If you want to assign a value later, you can do that too.myOptionalTuple[1] = 42; // Valid now