Home > front end >  typescript don't warn about a potentially undefined array?
typescript don't warn about a potentially undefined array?

Time:11-02

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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

  • Related