Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript:访问数组元素不会考虑未定义返回值的可能性_Typescript - Fatal编程技术网

Typescript:访问数组元素不会考虑未定义返回值的可能性

Typescript:访问数组元素不会考虑未定义返回值的可能性,typescript,Typescript,下面的代码通过了Typescript类型检查器(v2.9.1),但在运行时抛出一个TypeError interface Item { id: string } const list: Item[] = [{ id: 'a' }, { id: 'b' }]; const item = list[3]; // type: Item const itemId = item.id; // type: string 考虑到访问类型化数组中的元素总是会返回未定义的,item不应该是item:item |

下面的代码通过了Typescript类型检查器(v2.9.1),但在运行时抛出一个
TypeError

interface Item { id: string }
const list: Item[] = [{ id: 'a' }, { id: 'b' }];
const item = list[3]; // type: Item
const itemId = item.id; // type: string
考虑到访问类型化数组中的元素总是会返回
未定义的
,item不应该是
item:item |未定义的
,这会迫使您执行空检查吗

更让我惊讶的是,以下内容也包括类型检查:

const item2: Item | undefined = list[3];
const item2Id = item2.id;
尽管强制转换返回值成功地使类型检查失败:

const item3 = list[3] as Item | undefined;
const item3Id = item3.id; // [ts] Object is possibly 'undefined'.
创建显式类型的访问器函数也会捕获未定义的大小写,但会增加不必要的开销:

const getItem1 = (index: number, items: Item[]): Item | undefined => items[index];
const item3 = getItem1(3, list);
const item3Id = item3 && item3.id;

这是已知的typescript限制吗?是否有处理这种情况的推荐模式或库?

这是故意的行为

更让我惊讶的是,以下内容也包括类型检查:

const item2: Item | undefined = list[3];
const item2Id = item2.id;
您已禁用
复选框
;试着打开它。

TS4.1之前的答案: 您已经发现索引签名不会像可选属性那样向元素类型添加
| undefined
。创建一个编译器选项就可以做到这一点。您可以阅读该建议中的评论;它们与其他问题有关,但普遍认为高假阳性率将使其几乎毫无用处

还提到,您可以手动向元素类型添加
| undefined

const list: (Item | undefined)[] = [{ id: 'a' }, { id: 'b' }];
它将按照您的预期运行,不会影响整个语言


TS 4.1的更新:
TypeScript 4.1引入了一个以这种方式实现中的建议以解释
未定义的
。请注意,该功能将不会作为
--strict
编译器选项集的一部分启用,并被称为“迂腐的索引签名”,因为在程序员可能不期望或不希望的情况下,它最终会抱怨
未定义的
的可能性。

hmm,我确实有
strictNullChecks
关于:
const item:item=undefined
没有类型检查。这是预期行为的任何其他原因?啊,好的
(Item | undefined)[
似乎是一个很好的方法,尽管像map这样的数组方法必须显式地将项目函数的Item参数标记为未定义:
list.map((Item)=>Item!.id)
我一直在使用这种方法:在这种情况下,首选
数组
语法