gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:27:42 25 4
gpt4 key购买 nike

以下代码通过了 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

鉴于访问类型化数组中的元素总是返回undefined,item 不应该是item: Item | undefined,这会强制您进行 null 检查?

更让我吃惊的是,下面还有类型检查:

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 的已知限制吗?是否有推荐的模式或库来处理这种情况?

最佳答案

TS 4.1 更新:

TypeScript 4.1 引入了一个 --noUncheckedIndexedAccess compiler flag实现了 microsoft/TypeScript#13778 中的建议以这种方式解释 undefined。请注意,该功能不会作为 --strict 编译器选项集的一部分启用,并且被称为“迂腐的索引签名”,因为它最终会提示 undefined< 的可能性 在程序员可能不期望或不希望它的情况下。


TS4.1 前答案:

您发现索引签名不添加| undefined 以可选属性的方式添加到元素类型。建议在 microsoft/TypeScript#13778创建一个可以执行此操作的编译器选项。您可以阅读该建议中的评论;它们与其他问题有关,但共识是高误报率会使它几乎毫无用处。

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

const list: (Item | undefined)[] = [{ id: 'a' }, { id: 'b' }];

这将按照您的预期运行,而不会影响整个语言。

关于 typescript :访问数组元素不考虑未定义返回值的可能性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50647399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com