TypeScript 中 Tuple type of length has no element at index X 错误
当我们在 TypeScript 中声明一个元组并尝试访问一个不存在的索引处的元素时,会出现错误“Tuple type of length has no element at index”。 要解决该错误,需要调整元组的长度或改为声明 type[]
。
下面是发生上述错误的示例。
const arr: [string] = ['example'];
// ⛔️ Error: Tuple type '[string]' of length
// '1' has no element at index '1'.ts(2493)
console.log(arr[1]);
我们声明了一个只包含单个元素的元组,并试图访问索引为 1 的元素。
数组(和元组)的索引是从零开始的,因此元组在索引 0 处没有元素,类型检查器会抛出错误。
如果需要声明数组而不是元组,请使用以下语法。
const arr: string[] = ['example'];
console.log(arr[1]); // 👉️ undefined
请注意
,我们将特定类型的数组声明为Type[]
而不是[Type]
。
以下示例说明了如何声明多种类型的数组和对象数组。
// ✅ Array of mixed types
const mixedArr: (string | number)[] = ['hello', 100];
// ✅ Array of objects
const arrOfObjects: { id: number; name: string }[] = [
{
id: 1,
name: 'Tom',
},
{
id: 2,
name: 'James',
},
];
如果我们打算使用元组,则必须调整元组的长度或我们访问元组的索引。
const arr: [string, string] = ['hello', 'world'];
console.log(arr[1]); // 👉️ "world"
上面的示例声明了一个包含 2 个字符串类型元素的元组。
元组类型允许我们用固定数量的元素来表达一个数组,这些元素的类型是已知的,但可以不同。
这很有用,因为如果你不正确地初始化数组,你会得到一个错误。
// ⛔️ Error: Type 'number' is not
// assignable to type 'string'.ts(2322)
const arr: [string, string] = ['hello', 100];
在现有索引处访问元组元素时,TypeScript 知道值的类型。
const arr: [string, number] = ['hello', 100];
console.log(arr[0].toUpperCase()); // 👉️ "HELLO"
console.log(arr[1].toFixed(2)); // 👉️ 100.00
正如我们所见,当我们尝试访问不存在的索引处的元组元素时,TypeScript 也会提醒我们。
const arr: [string, number] = ['hello', 100];
// ⛔️ Error: Tuple type '[string, number]'
// of length '2' has no element at index '2'.ts(2493)
console.log(arr[2]);
如果使用 const
关键字来声明元组,则必须使用已为其指定类型的所有值来初始化数组。
// ⛔️ Error: Type '[string]' is not
// assignable to type '[string, number]'.
const arr: [string, number] = ['hello'];
如果在初始化数组时没有所有必要的值,请使用 let
关键字来声明元组。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。