[英]typescript don't warn about a potentially undefined array?
I have a question about how could I leverage typescript to warn about an array that could cause a run time error ?我有一个关于如何利用打字稿警告可能导致运行时错误的数组的问题? I have the following code I usually use a question mark after the array .. but should typescript know that this might cause a runtime error ?
我有以下代码我通常在数组后使用问号..但是打字稿应该知道这可能会导致运行时错误吗?
// cause run time erorr.. context.arr[props.id].includes(select) // no run time erorr context.arr[props.id]?.includes(select)
?.
is optional chaining , which will properly chain with what follows if the expression on the left-hand side is defined (not undefined/null), and will evaluate to undefined
otherwise:是optional chaining ,如果左侧的表达式已定义(不是 undefined/null),它将与后面的内容正确链接,否则将评估为
undefined
:
context.arr[props.id]?.includes(select)
// if context.arr[props.id] is undefined/null, equivalent to:
undefined
// (does not throw an error)
// if context.arr[props.id] is notundefined/null, equivalent to:
context.arr[props.id].includes(select)
So, as long as TypeScript can see that, when context.arr[props.id]
isn't undefined/null, it'll be an array, that statement is perfectly type-safe.因此,只要 TypeScript 可以看到,当
context.arr[props.id]
不是 undefined/null 时,它将是一个数组,该语句是完全类型安全的。 (though, TypeScript has problems with .includes
, but that's another issue) (虽然,TypeScript有
.includes
问题,但这是另一个问题)
You can enable the desired behavior by turning on Checked Indexed Accesses (available since 4.1 version).您可以通过打开Checked Indexed Accesses (自 4.1 版本起可用)来启用所需的行为。 Under this mode, indexed access is considered potentially undefined.
在这种模式下,索引访问被认为可能是未定义的。 To enable it - set
noUncheckedIndexedAccess
compiler option to true
.要启用它 - 将
noUncheckedIndexedAccess
编译器选项设置为true
。
const arr = ['foo', 'bar']
// Expect error: Object is possibly 'undefined'.
arr[1].includes('test')
// OK
arr[1]?.includes('test')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.