typescript - 让打字稿警告不要访问可能为空数组的第一项
问题描述
const test: string[] = [];
test[0].length
此代码不会引发 TypeScript 错误。你怎么能让打字稿警告一个字符串实际上可能不存在于给定索引的事实?
解决方案
您可以使用此解决方法,将数组项设置为尽可能未定义:
const test: (string | undefined)[] = [];
test[0].length; // error
if(test[0]) {
test[0].length; // good
}
我没有找到任何可以满足这种需求的 eslint 规则:(
推荐阅读
- sbt - Sbt clean compile:无法捕获编译错误
- javascript - 如何将 PHP 模型作为源添加到 jQuery 自动完成源?
- node.js - 设置 cookies-parser node.js express 后无法连接到 localhost
- django - Django:按顺序(有效)对过滤查询集的整数字段进行编号
- javascript - 如何在反应js中调用两个有条件的API?
- angular - 实现带角度的自动动画滚动
- typescript - Typescript NetworkInformation 类型不包含所有属性
- python - 使用 XSD 中的属性字段获取标签的路径
- database - 使用自己的云环境而不是 Snowflake 托管的 s3 来存储数据
- jenkins - 如何在从詹金斯运行 RobotFramework 时禁用 [WARN] 消息以记录到控制台