23

I noticed that in the following example the type of c is number, not number|undefined:

const a:number[] = []
const c = a[1]

In other words, I can do

let b:number = a[1]

without a problem, while a[1] can be undefined. This may cause hidden bugs in code. Am I missing something?

3
  • accessing an array by index can indeed cause undefined. It's up to you to check this and avoid errors Commented Sep 29, 2020 at 9:45
  • JS/Typescript is a bit of a special case there, because in most other languages you get an exception or a segfault when you try to access an index out of bounds. So in any other language you would have to check, whether you can securely access that index, thus, you should also in JS/Typescript. Commented Sep 29, 2020 at 10:00
  • 3
    @Ric, derpirscher, yes I understand this, but what I expect from Typescript is that it would warn me about all the dangerous places in my code, otherwise I would use vanilla JavaScript adding all necessary checks. Anyway, I'm glad they are going to add this to the future version. Commented Sep 29, 2020 at 14:09

1 Answer 1

27

In the next version of typescript (4.1) you'll be able to enable the desired behavior with the noUncheckedIndexedAccess (aka pedantic index signature checks) compiler option:

  • Any indexed access expression obj[index] used in a read position will include undefined in its type, unless index is a string literal or numeric literal with a previous narrowing in effect
  • Any property access expression obj.prop where no matching declared property named prop exists, but a string index signature does exist, will include undefined in its type, unless a previous narrowing on obj.prop is in effect

So a[1] will result in number | undefined. You can already try it by installing typescript@next

Announcement

PR

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

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.