Skip to content

Unexpected error: TS2322: Type 'string | undefined' is not assignable to type 'string'Β #55206

Closed as not planned
@britalmeida

Description

@britalmeida

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions