0

In this code

const arr = ['hello', 'world'];
const x = arr[2];
const y = arr[0.5];

arr is a string[], and 10 and 0.5 are numbers, so TS implies that 10 and 0.5 can index arr, therefore inferring that x and y are strings too, while at runtime they'll be undefined.

Is there a configuration option I can write in my tsconfig.json that basically tells typescript "if you're not sure that arr: T[] has an element at i, do not infer that arr[i] is a T"?

Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
  • Does this answer your question? [How to declare a Fixed length Array in TypeScript](https://stackoverflow.com/questions/41139763/how-to-declare-a-fixed-length-array-in-typescript) – jonrsharpe Jun 13 '21 at 13:56
  • No, as you can see from [this playground](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwTAvDMBTA7jAgkuATwB4wBXAWwCMMEA+ACgGYBKAKFElgA9V4kA2gEYADAF0O4aDEJ9ECASIB0AVjFA), this doesn't stop TS from inferring wrong types, even if the initial array size has been annotated – Nino Filiu Jun 13 '21 at 14:00
  • Please do keep reading past the first line. – jonrsharpe Jun 13 '21 at 14:01

1 Answers1

1

TypeScript 4.1 introduced support for checked indexed accesses, which can be enabled via the --noUncheckedIndexedAccess compiler option. If you turn that on, you get this behavior:

const arr = ['hello', 'world'];
const x = arr[10] // number | undefined
console.log(x.toUpperCase()) // compiler error
//          ~ <-- object is possibly undefined

console.log(x?.toUpperCase()) // okay

which is what you're looking for. This option is not included in the --strict suite of type checking features, because it can make the compiler complain even for code which is generally considered safe:

for (let i = 0; i < arr.length; i++) {
    console.log(arr[i].toUpperCase()) // error!
    // -------> ~~~~~~
    // arr[i] is possibly undefined
}

So you'll have to decide if your desired behavior is worth the possible false warnings from the type checker, and if so, turn on --noUncheckedIndexedAccess explicitly.

Playground link to code

jcalz
  • 264,269
  • 27
  • 359
  • 360