Description
Bug Report
π Search Terms
TS2322 ; "undefined is not assignable to type" ; array iteration ; noUncheckedIndexedAccess
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries
β― Playground Link
Playground link with relevant code
π» Code
With noUncheckedIndexedAccess=true
function testfunc(urls: string[]): void {
for (let i = 0; i < urls.length; i++) {
const image = new Image();
image.src = urls[i]; // Error: 'undefined' is not assignable to type 'string'
}
}
π Expected behavior
urls
is declared as an array of string
, not string | undefined
, therefore I expect the assignment inside the function to be safe and an error on the calling side of the function if someone tries to pass in an array with potentially undefined things in it.
I don't understand why the for loop indexing makes it unsafe? Or how I should write my code then?
I have looked at the option documentation, at stack overflow and at the internet for far too long :))
I don't understand the documentation example (I don't know about 'unknown properties').
- Could it be that
noUncheckedIndexedAccess
is incorrectly adding 'undefined' for this case? - Or is it doing the correct thing? It's my confusion then, but if so, is it possible to improve the documentation so I can understand why the option is useful and how it applies to my case which has no unknown properties or fields in the type? (and how I should be writing that code snippet correctly then).
Another minimal example that I would not expect to cause an error:
const names = ['apple', 'banana'];
let s : string;
s = names[0]; // Error: 'undefined' is not assignable to type 'string'
Background context:
I'm not a JS or TS expert. I have recently started using TypeScript and porting a JS project to it. I incrementally enabled all error reporting options and strictness that I found :)
Obviously it must have been my error and messy enabling of options, but I'm pretty sure that everything worked at some point and then I noticed this error days later. It was quite time consuming to search for it and track it to the for loop and specifically to noUncheckedIndexedAccess
.