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)

3
  • If it's the context.arr[props.id] that might be undefined, that's just fine Commented Nov 1, 2021 at 2: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 ? Commented Nov 1, 2021 at 2: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 Commented Nov 2, 2021 at 6:18

2 Answers 2

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


Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.