Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Typescript严格模式下可能未定义的数组引用_Arrays_Typescript_Types_Undefined - Fatal编程技术网

Arrays Typescript严格模式下可能未定义的数组引用

Arrays Typescript严格模式下可能未定义的数组引用,arrays,typescript,types,undefined,Arrays,Typescript,Types,Undefined,在工作中,我们使用带有严格空检查的Typescript帮助捕获由空/未定义变量引起的异常。然而,我们最近遇到了一个Typescript似乎忽略的bug。下面的代码演示了这一点: 接口IMyObj{ foo:string; } 常量myArr:IMyObj[]=[]; 常量myObjProp=myArr[0].foo; 控制台日志(myObjProp); Typescript将毫无怨言地编译此文件,但运行时显然会抛出一个类型错误: Uncaught TypeError: Cannot read

在工作中,我们使用带有严格空检查的Typescript帮助捕获由空/未定义变量引起的异常。然而,我们最近遇到了一个Typescript似乎忽略的bug。下面的代码演示了这一点:

接口IMyObj{
foo:string;
}
常量myArr:IMyObj[]=[];
常量myObjProp=myArr[0].foo;
控制台日志(myObjProp);
Typescript将毫无怨言地编译此文件,但运行时显然会抛出一个类型错误:

Uncaught TypeError: Cannot read property 'foo' of undefined
当然,我们可以将代码库中的所有数组类型定义为
(IMyObj | undefined)[
,而不是
IMyObj[]
,但这似乎也很容易出错,因为很容易遗漏一种

有没有办法让Typescript检测可能未定义的引用,如
myArr[0]

有没有办法让Typescript检测可能未定义的引用,如myArr[0]


不,而且它不太可能在TypeScript中实现,请参阅的讨论。另请参见。

您可以添加此选项

"noUncheckedIndexedAccess": true,  /* Include 'undefined' in index signature results */
进入
“compilerOptions”
对象的tsconfigfile.json捕获错误取决于未定义的数组项