Reputation: 2285
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)
Upvotes: 1
Views: 603
Reputation: 37918
You can enable the desired behavior by turning on Checked Indexed Accesses (available since 4.1 version). Under this mode, indexed access is considered potentially undefined. To enable it - set noUncheckedIndexedAccess
compiler option to true
.
const arr = ['foo', 'bar']
// Expect error: Object is possibly 'undefined'.
arr[1].includes('test')
// OK
arr[1]?.includes('test')
Upvotes: 2
Reputation: 370679
?.
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:
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. (though, TypeScript has problems with .includes
, but that's another issue)
Upvotes: 1