You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何TypeScript中T[number]不会返回undefined?

为什么元组的T[number]在开启noUncheckedIndexedAccess时不包含undefined?

这个差异的核心在于TypeScript对元组类型和普通数组类型的索引处理逻辑完全不同:

  • 普通数组类型(比如number[])的number索引代表所有可能的数字,开启noUncheckedIndexedAccess后,TypeScript认为任意索引的访问都可能越界,因此Arr[number]会被推断为number | undefined。
  • 但元组是固定长度、各位置类型明确的特殊数组类型,TypeScript会把元组的有效索引严格限制为它已定义的那些(比如[1,2]的有效索引仅为0和1)。当你使用T[number]时,TypeScript只会遍历元组的有效索引对应的类型,不会考虑超出长度的索引场景,所以最终结果是1 | 2,而非包含undefined。

举个对比例子更直观:

// 普通数组,开启noUncheckedIndexedAccess后
type NormalArr = number[];
type NormalUnion = NormalArr[number]; // number | undefined

// 元组
type Tuple = [1, 2];
type TupleUnion = Tuple[number]; // 1 | 2

如果确实需要让元组的索引访问结果包含undefined,可以手动将元组转为普通数组类型后再处理:

type GetUnionWithUndefined<T extends any[]> = Array<T[number]>[number];
type Foo = GetUnionWithUndefined<[1, 2]>; // 1 | 2 | undefined

内容的提问来源于stack exchange,提问作者lefty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 21:18:13