Skip to content

Can't infer array.prototype.find as not undefined when array.prototype.some is true in the upper if clauseΒ #60473

Description

πŸ”Ž Search Terms

find some undefined

πŸ•— Version & Regression Information

I tried TS Playground with nightly.

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.8.0-dev.20241110#code/GYVwdgxgLglg9mABMGAnAzlAMgUylHVACigENUBzPdALkU1RjAoG0BdASkQG8AoRRDGCIS5KlHQA6dHAC2OUZTyIAvAD5EZJVEkAbHMygALRBoCMHDnwECA9LfpMIOTWOqIjpAG4uZ8xDj68mASiADuRnDoLvqGJuQusnCoLsakSGYANMhw4AAmiLIgmIhgcFCIAEYuAOT5OChgOHk1VTgQpMUuAA4peTAdBILo9KTy-DYQCCXAuWAFKq7aUo15RIriqhpa4noGFMamiBYcANwTdg6VIBWz+YUwmKQA1ga6AJ6CYMCEI1Bw9CgjGYAB96o1mpojMUcrpdHAwkwKIgUlAQKgkMZUAiRoRsagLii8OikHd5iwAAxsc4CAC+E1RJMQACJmedaUA

πŸ’» Code

function firstLetter(targets: string[]) {
  if (targets.some(target => target.length > 1)){
    // since targets have some elements whose length are more than 1, found must not be 'undefined' because predicate is same
    const found = targets.find((target => target.length > 1));
    // but found mistakenly infers to string|undefined thus following return throws error
    return found[0];
  }
  return "";
}

πŸ™ Actual behavior

found[0] throws error "'found' is possibly 'undefined'.(18048)"
Because some and find has same predicate and some is true, find must return string.

πŸ™‚ Expected behavior

The code can be compiled without error.

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions