让打字稿警告不要访问可能为空的数组的第一项

时间:2019-10-04 08:23:38

标签: typescript

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

此代码不会引发TypeScript错误。您如何让打字稿针对某个字符串在给定索引处实际上不存在的事实发出警告?

1 个答案:

答案 0 :(得分:1)

您可以使用此替代方法,将数组项设置为未定义:

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

test[0].length; // error

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

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