question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

`Array.prototype.at` should return a more precise type when operating on a tuple

See original GitHub issue

Suggestion

Extracted out of #45512

🔍 Search Terms

List of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily and help provide feedback.

Tuple Array.prototype.at

✅ Viability Checklist

My suggestion meets these guidelines:

  • This wouldn’t be a breaking change in existing TypeScript/JavaScript code
  • This wouldn’t change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn’t a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript’s Design Goals.

⭐ Suggestion

at called on a tuple should work consistently with how index access on tuples works.

const tuple = [1, 2, 3] as const;
const element = tuple.at(1);
type T = typeof element; // currently `number | undefined`, ideally should be `2`

// Should also work with negatives.
const element2 = tuple.at(-1);
type U = typeof element2; // ideally should be `3`

// Compiler error or `undefined` for out of bounds numbers?
const element3 = tuple.at(100); // should be compiler error or
type V = typeof element3; // should be undefined

📃 Motivating Example

This is how tuples work when using index access.

💻 Use Cases

Preferring .at(index) to [index].

Partial Hack Solution

as suggested by @djmisterjon

interface ReadonlyArray<T> {
    /**
     * Returns the item located at the specified index.
     * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
     */
    at<U extends number>(index: U): this[U];
}

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:6
  • Comments:12 (3 by maintainers)

github_iconTop GitHub Comments

6reactions
jcalzcommented, Jan 30, 2022

You can get negative indices to work for tuples (template literals to drop the minus sign and then use the numberlike string to index into a shifted reversed tuple), but nobody would want this in the actual TS library. Still, enjoy:

⚙🛠
type Reverse<T extends readonly any[], U extends any[] = []> =
  T extends readonly [infer F, ...infer R] ? Reverse<R, [F, ...U]> : U

type At<T extends readonly any[], I extends number> =
  `${I}` extends `-${infer J}` ? [never, ...Reverse<T>] extends infer R ? J extends keyof R ? R[J] :
  undefined : never : T[I];

interface ReadonlyArray<T> {
  at<I extends number>(index: I): At<this, I>;
}
interface Array<T> {
  at<I extends number>(index: I): At<this, I>;
}
const tuple = [1, 2, 3] as const;
const element = tuple.at(1);
type T = typeof element; // 2
const element2 = tuple.at(-1);
type U = typeof element2; 3
const element3 = tuple.at(100); 
type V = typeof element3; // undefined

Playground link

3reactions
jcalzcommented, Feb 1, 2022

@jcalz ow my soul

@RyanCavanaugh ah yes, the theological argument for #26382

Read more comments on GitHub >

github_iconTop Results From Across the Web

Array.prototype.at() - JavaScript - MDN Web Docs
The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers.
Read more >
Why does the argument for Array.prototype.includes ...
I don't understand why a function ( Array.prototype.includes() ) made to check if an element is found in an array, should have knowledge...
Read more >
Stage 3 Proposal: Array.prototype.at - Hacker News
So a dedicated numeric type for probability value is nothing more than a nice-to-have. ... Array.prototype.at = function (i) { return i <...
Read more >
تويتر \ Wes Bos على تويتر: "Got to use TypeScript interface ...
TypeScript doesn't support the .at() method on readonly array / const ... `Array.prototype.at` should return a more precise type when operating on a...
Read more >
Hacks for Creating JavaScript Arrays - freeCodeCamp
In JavaScript, there are not so many complex data types — you simply have ... The most popular method for creating arrays is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found