1

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)
Richardson
  • 1,804
  • 10
  • 38
  • If it's the `context.arr[props.id]` that might be undefined, that's just fine – CertainPerformance Nov 01 '21 at 02:04
  • @CertainPerformance it is created after an action... but the function that does the check runs as well , but shouldn't typescript be warning about this ? – Richardson Nov 01 '21 at 02:07
  • @CertainPerformance it possible to warn about `context.arr[props.id]` potentially undefined by enabling `noUncheckedIndexedAccess`. It can introduce a lot of noise in existing code base, but still possible – Aleksey L. Nov 02 '21 at 06:18

2 Answers2

2

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')

Playground


Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
1

?. 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)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320