以下代码在Typescript类型检查器(v2.9.1)中通过,但在运行时抛出TypeError。
interface Item { id: string }
const list: Item[] = [{ id: 'a' }, { id: 'b' }];
const item = list[3]; // 类型: Item
const itemId = item.id; // 类型: string
考虑到访问类型化数组中的元素可能始终返回undefined,item应该是item: Item | undefined,这将强制你进行空值检查,难道不应该吗?
更令我惊讶的是,以下代码也通过类型检查:
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'.
创建一个显式类型的访问器函数也可以捕获到undefined的情况,但会增加不必要的开销:
const getItem1 = (index: number, items: Item[]): Item | undefined => items[index]; const item3 = getItem1(3, list); const item3Id = item3 && item3.id;
这是Typescript的已知限制吗?有没有推荐的模式或库来处理这种情况?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号