Mike
Mike

Reputation: 2153

Why in TypeScript an array element accessed by index doesn't have "undefined" in its type?

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?

Upvotes: 22

Views: 6196

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37938

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

Upvotes: 26

Related Questions