首页 > 解决方案 > 让打字稿警告不要访问可能为空数组的第一项

问题描述

const test: string[] = [];
test[0].length

此代码不会引发 TypeScript 错误。你怎么能让打字稿警告一个字符串实际上可能不存在于给定索引的事实?

标签: typescript

解决方案


您可以使用此解决方法,将数组项设置为尽可能未定义:

const test: (string | undefined)[] = [];

test[0].length; // error

if(test[0]) {
  test[0].length; // good
}

我没有找到任何可以满足这种需求的 eslint 规则:(


推荐阅读