Last updated: Feb 27, 2024
Reading timeยท3 min
The error "Tuple type of length has no element at index" occurs when you declare a tuple in TypeScript and try to access an element at an index that doesn't exist.
To solve the error, adjust the length of the tuple or declare a type[]
instead.
Here is an example of how the error occurs.
const arr: [string] = ['bobbyhadz.com']; // โ๏ธ Error: Tuple type '[string]' of length // '1' has no element at index '1'.ts(2493) console.log(arr[1]);
We declared a tuple that only
contains a single element and tried to access the element at index 1
.
1
and the type checker throws the error.The first element in a tuple has an index of 0
and the last element has an
index of tuple.length - 1
.
If you need to declare an array instead of a tuple, use the following syntax.
const arr: string[] = ['bobbyhadz.com']; console.log(arr[1]); // ๐๏ธ undefined
Type[]
and not [Type]
.Here are examples of how you would declare an array of multiple types and an array of objects.
// โ Array of mixed types const mixedArr: (string | number)[] = ['hello', 100]; // โ Array of objects const arrOfObjects: { id: number; name: string }[] = [ { id: 1, name: 'Bobby', }, { id: 2, name: 'Hadz', }, ];
If you intended to use a tuple, you would have to adjust the tuple's length or the index at which you're accessing the tuple.
const arr: [string, string] = ['bobby', 'hadz']; console.log(arr[1]); // ๐๏ธ "hadz"
The example declares a tuple that contains 2
elements of type string
.
This is useful because if you initialize the array incorrectly you'll get an error.
// โ๏ธ Error: Type 'number' is not // assignable to type 'string'.ts(2322) const arr: [string, string] = ['bobbyhadz.com', 100];
When accessing a tuple element at an existing index, TypeScript knows the type of the value.
const arr: [string, number] = ['bobbyhadz.com', 100]; console.log(arr[0].toUpperCase()); // ๐๏ธ "BOBBYHADZ.COM" console.log(arr[1].toFixed(2)); // ๐๏ธ 100.00
As we saw, TypeScript also alerts us when we try to access a tuple element at a non-existent index.
const arr: [string, number] = ['bobbyhadz.com', 100]; // โ๏ธ Error: Tuple type '[string, number]' // of length '2' has no element at index '2'.ts(2493) console.log(arr[2]);
If you use the const
keyword to declare the tuple, you have to initialize the
array with all of the values for which you've specified a type.
// โ๏ธ Error: Type '[string]' is not // assignable to type '[string, number]'. const arr: [string, number] = ['bobbyhadz.com'];
If you don't have all of the necessary values when initializing the array, use
the let
keyword to declare the tuple.
You can learn more about the related topics by checking out the following tutorials: