-
-
Notifications
You must be signed in to change notification settings - Fork 660
Add ArrayAt type
#1279
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
base: main
Are you sure you want to change the base?
Add ArrayAt type
#1279
Conversation
Co-authored-by: Wei Wen <[email protected]>
|
Can you summarize how it's simpler? Any downsides? |
Yeah yeah, I'll add all the details once I make the PR "Ready for review". |
|
I'm a bit confused by the documentation: It shows some results as union, which it would not be the real translation of JS Array.at right? Is the below example something similar to what you want to achieve? import { ArraySlice, GreaterThan, IsNegative, LastArrayElement } from 'type-fest';
export type IsPositive<N extends number> = IsNegative<N> extends true ? false : true;
type MakePositive<N extends number> =
IsPositive<N> extends true ? N : `${N}` extends `${infer _}${infer R extends number}` ? R : N;
type ArrayAt<TArray extends readonly unknown[], TIndex extends number> =
IsPositive<TIndex> extends true
? TArray[TIndex]
: GreaterThan<number & MakePositive<TIndex>, TArray['length']> extends true
? undefined
: ArraySlice<TArray, TIndex>[0];
type Arr = [1, 2 | undefined, 3];
type Test = ArrayAt<Arr, 1>; // 2 | undefined
type Test2 = ArrayAt<Arr, -4>; // undefined
type Test3 = ArrayAt<Arr, -3>; // 1
type Test4 = ArrayAt<Arr, -2>; // 2 | undefined
type Test5 = ArrayAt<Arr, -1>; // 3
type Test6 = ArrayAt<Arr, 4>; // undefined |
@andr3medeiros For array types that contain optional elements or rest element, the answer could be a union because the type could hold different values at runtime. For example, the array type ['a', 'b', 'c', 'd']
['a', 'b', 'c', 1, 'd']
['a', 'b', 'c', 1, 2, 'd']
['a', 'b', 'c', 1, 2, 3, 'd']Now, if you index ['a', 'b', 'c', 'd'].at(-3) // 'b'
['a', 'b', 'c', 1, 'd'].at(-1) // 'c'
['a', 'b', 'c', 1, 2, 'd'].at(-1) // 1
['a', 'b', 'c', 1, 2, 3, 'd'].at(-1) // 2So, therefore the final result of |
|
@som-sm you're right about the array spread problem. But it got me thinking on this outcome thing. We're talking about touples, not arrays right? Array items are unpredictable. Given that I believe |
@andr3medeiros Both arrays and tuples. Moreover, you can argue that something like
Yeah, correct! This PR is still a WIP, but you can go through the test cases to better understand the different scenarios. |
This PR proposes a significantly simpler implementation for #1105. Closes #369.
Opened a new PR as I didn’t want to overwrite the existing one, since it introduces several helper types that might be useful in general. We could potentially repurpose that PR to expose some of those utility types.