Skip to content

Instantly share code, notes, and snippets.

@aneurysmjs
Created August 7, 2022 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aneurysmjs/4aa594ee2fc1c470c34083c444c58e3a to your computer and use it in GitHub Desktop.
Save aneurysmjs/4aa594ee2fc1c470c34083c444c58e3a to your computer and use it in GitHub Desktop.
'noUncheckedIndexAccess' Typescript compiler option
function upper(arr: string[]) {
for (let i = 0; i < arr.length; i += 1) {
let str = arr[i];
console.log(str.upperCase())
}
}
upper(['foo', 'bar', 'baz']);
// In Typescript when index into an array you get the element type of the array.
// but technically that isnt really safe, because Javascript has funky ways of creating
// arrays with holes in it.
// this Typescript will catch up
upper(['foo', , 'baz']); // type 'undefined' is not assignable to type 'string'
// but if instead we do this:
let a = [];
a[42] = 'hello';
upper(a)
// at this point we have created an array with 41 holes and the 42nd element is present
// and the length is 42 and thats awfully hard for a typechecker to comprehend.
// it is problem that is not solvable meaningfully in a typechecker.
// { "noUncheckedIndexAccess": true } this basically reflects the reality of the world
// that whenever you fish something out of an array at a computed index you might
// get undefined because you might actually access an element that isnt there and it is
// up to you now to ensure that you handle that, for example by giving a default value
function upper(arr: string[]) {
for (let i = 0; i < arr.length; i += 1) {
let str = arr[i] ?? '';
console.log(str.upperCase())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment