Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ReadonlyArray] Add types for .at() #101

Open
wants to merge 12 commits into
base: main
Choose a base branch
from

Conversation

Sheraff
Copy link

@Sheraff Sheraff commented Mar 6, 2023

This PR solves #100

const a = [false, 1, '2'] as const

const b = a.at(0)
//    ^? const b: false

const c = a.at(-1)
//    ^? const c: "2"

See issue for a more complete description

@Sheraff
Copy link
Author

Sheraff commented Mar 7, 2023

One case remain unhandled, and I'd love some help on it:

With "strictNullChecks": true, the following type should include undefined but doesn't.

const arr = [false, 1, '2'] as const;
const index: number = 1
const a = arr.at(index)
//    ^? const a: false | 1 | "2"

@DeepDoge
Copy link

DeepDoge commented Aug 21, 2023

Did a PR: Sheraff#1

This will return undefined regardless if strictNullChecks is true or false.

But this is already the behaviour of native ReadonlyArray .at().

As seen here:

interface Array<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(index: number): T | undefined;
}

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(index: number): T | undefined;
}

Also fixed an issue with index union types, and added tests for it.

Issue was being caused by how Subtract util type works with unions types:

type Foo = Subtract<10, 1 | 2> 
// Foo should give `9 | 8` but gives `9` only

Also handled the cases where index number is a "float" and not an "int" correctly, based on how .at() handles them

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants