ts-reset icon indicating copy to clipboard operation
ts-reset copied to clipboard

[ReadonlyArray] Add types for `.at()`

Open Sheraff opened this issue 2 years ago • 2 comments

This PR solves https://github.com/total-typescript/ts-reset/issues/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 avatar Mar 06 '23 20:03 Sheraff

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"

Sheraff avatar Mar 07 '23 11:03 Sheraff

Did a PR: https://github.com/Sheraff/ts-reset/pull/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

DeepDoge avatar Aug 21 '23 10:08 DeepDoge