Typescript Tuples, and how they work
Tuple already exists.
How to define a Tuple in Typescript
Defining a Tuple in Typescript is straightforward. All you need to do, is define the type as an array of known types. For example, the following constant is a tuple:
const myTuple:[ string, number ] = [ "some", 15 ]
When we define first define a Tuple, it should be an array, it should have a known length, and each element should have a known type.
Defining an Array of Tuples in Typescript
We can also define an array of Tuples in Typescript. This is done by adding
 to the end of our Tuple type definition:
let myTuple:[ string, number ] = [ [ "some", 15 ], [ "other", 20 ], [ "tuple", 50 ] ];
Mutating a Typescript Tuple
let myTuple:[ string, number ] = [ "some", 15 ] myTuple = 20;
If we tried to change an element of our Tuple to a different type, however, we would get a type error. For example, if we tried to run
myTuple = "string", we would get the following error:
Type 'string' is not assignable to type 'number'.
Interestingly, if we try to extend the length of a Tuple by using
myTuple.push(5), we will not get an error unless we are using
push() on a constant, or if the type we use is not in the original type list.
This means that once a Tuple is defined, it no longer has to be of known length, as long as each element conforms to one of the original types we defined when first creating our Tuple. So
myTuple.push(5) works in the case above - but
myTuple.push(true) does not as
Creating read only Tuples in Typescript
If we want to create an immutable, read only Tuple in Typescript, we can use the
readonly keyword when defining our Tuple.
To do that, we would define our variable as this:
const myArray:readonly[number, string] = [10, 'test'];
If we try to mutate or change this Tuple, we will get an error. For example, if we use
push() now, we will get the following error:
Property 'push' does not exist on type 'readonly [number, string]'.
myArray = 15 will return the following error:
Cannot assign to '0' because it is a read-only property.
More Tips and Tricks for Typescript
- How TypeScript Default Parameters Work
- How Template Literal Types work in TypeScript
- How the TypeScript Parameters Type Works
- How the TypeScript NonNullable Type Works
- How the TypeScript ReturnType Type works
- How to setup a new Project in Typescript
- Typescript Tuples, and how they work
- How Typescript Generic Types Work
- How the TypeScript Extract Type Works
- TypeScript Optional Parameters