首页 > 解决方案 > 为什么 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;
} 

标签: typescripttypechecking

解决方案


默认情况下,TS 不检查该值是否存在于动态数组 ( string[]) 中的特定索引下。为了确保类型安全,您可以执行以下操作之一(或两者):

  1. 将返回类型缩小为[string] | [](因为这是您的函数实际返回的内容)。
  2. 在您的 TS 配置中设置noUncheckedIndexedAccessundefined (这将强制您在访问索引时检查元素)。

推荐阅读