Skip to content

Array.at() doesn't consider array length #63130

@johndeighan

Description

@johndeighan

🔎 Search Terms

I'm using deno, so here is its version and the TypeScript version it's using:

$ deno --version
deno 2.6.9 (stable, release, x86_64-pc-windows-msvc)
v8 14.5.201.2-rusty
typescript 5.9.2

This expression results in an error, but should not:

const lParts: string[] = [];
if (lParts.length > 0) && lParts.at(-1).endsWith('\n') ...

because obviously if an array has at least one item in it, there's an item in the next to last position and because of the way lParts is defined, the array cannot have any undefined items in it.

There is a workaround, though it shouldn't be needed, which is:

const lParts: string[] = [];
if (lParts.length > 0) && lParts.at(-1)?.endsWith('\n') ...

which avoids calling endsWith() if lParts.at(-1) were to return undefined (which it cannot)

🕗 Version & Regression Information

  • This changed between versions ______ and _______
  • This changed in commit or PR _______
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
  • I was unable to test this on prior versions because _______

⏯ Playground Link

No response

💻 Code

// Your code here

🙁 Actual behavior

It fails with an error

🙂 Expected behavior

It shouldn't give an error

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions