typescript - 为什么 Typescript 允许我这样做?数组没有长度检查
问题描述
为什么 Typescript 允许我使用任何数组元素而不强迫我检查索引是否有效?
这就是我的意思
function return_array(p:boolean):string[]{
return (p) ? ['s'] : [];
}
const arr = return_array(false);
arr[30].toUpperCase();
这显然会导致我出错
Cannot read property 'toUpperCase' of undefined
这是设计使然还是我遗漏了什么?
编辑
真正的功能是这样的:
function return_array(p:boolean):string[]{
// querying the db, it can return an empty array.
return db_response;
}
解决方案
默认情况下,TS 不检查该值是否存在于动态数组 ( string[]
) 中的特定索引下。为了确保类型安全,您可以执行以下操作之一(或两者):
- 将返回类型缩小为
[string] | []
(因为这是您的函数实际返回的内容)。 - 在您的 TS 配置中设置noUncheckedIndexedAccess
undefined
(这将强制您在访问索引时检查元素)。
推荐阅读
- oracle - APEX 基于过程创建表单
- c# - F# 异步 lambda 与 C# 异步模型互操作
- ios - RootViewController 过渡效果不起作用
- scala - 无法创建 Lagom HelloWorld 演示
- python - 如何抑制 HdfsCLI 的 INFO 日志?
- powerquery - 组记录 - 保留第一个开始日期(最旧)和最后一个结束日期(最近)
- c++ - 位掩码枚举值的替代解决方案
- xaml - 标签内容/ContentStringFormat 的本地化
- angularjs - Angular SPA 中的 subscribe() 未触发 Http 发布请求
- laravel - laravel 雄辩的 ORM 更新和删除