Skip to content

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.

2 participants