length 类型的元组在 TS 中索引 X 处没有元素
Tuple type of length has no element at index X in TS
当您在 TypeScript 中声明一个元组并尝试访问一个不存在的索引处的元素时,会出现错误“Tuple type of length has no element at index”。
要解决该错误,请调整元组的长度或改为声明一个type[]
。
下面是错误如何发生的示例。
const arr: [string] = ['bobbyhadz.com']; // ⛔️ Error: Tuple type '[string]' of length // '1' has no element at index '1'.ts(2493) console.log(arr[1]);
我们声明了一个仅包含单个元素的元组,并尝试访问 index 处的元素1
。
1
,类型检查器会抛出错误。元组中的第一个元素的索引为0
,最后一个元素的索引为tuple.length - 1
。
声明一个数组而不是一个元组
如果需要声明数组而不是元组,请使用以下语法。
const arr: string[] = ['bobbyhadz.com']; console.log(arr[1]); // 👉️ undefined
Type[]
and not [Type]
。// ✅ 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', }, ];
调整元组的长度或更正索引
如果您打算使用元组,则必须调整元组的长度或您访问元组的索引。
const arr: [string, string] = ['bobby', 'hadz']; console.log(arr[1]); // 👉️ "hadz"
该示例声明了一个包含2
type 元素的元组string
。
This is useful because if you initialize the array incorrectly you’d 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.
# Additional Resources
You can learn more about the related topics by checking out the following
tutorials: