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

fix(LastArrayElement): fix handling of the tuple with spread elements #727

Merged
merged 2 commits into from
Oct 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions source/last-array-element.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,26 @@ const array = ['foo', 2];

typeof lastOf(array);
//=> number

const array = ['foo', 2] as const;

typeof lastOf(array);
//=> 2
```

@category Array
@category Template literal
*/
export type LastArrayElement<Elements extends readonly unknown[]>
= number extends Elements['length']
? Elements extends ReadonlyArray<infer Element>
? Element
: never
: Elements extends readonly [...any, infer Target]
? Target
: never;
export type LastArrayElement<Elements extends readonly unknown[], ElementBeforeTailingSpreadElement = never> =
// If the last element of an array is a spread element, the `LastArrayElement` result should be `'the type of the element before the spread element' | 'the type of the spread element'`.
Elements extends readonly []
? ElementBeforeTailingSpreadElement
: Elements extends readonly [...infer U, infer V]
? V
: Elements extends readonly [infer U, ...infer V]
// If we return `V[number] | U` directly, it would be wrong for `[[string, boolean, object, ...number[]]`.
// So we need to recurse type `V` and carry over the type of the element before the spread element.
? LastArrayElement<V, U>
: Elements extends ReadonlyArray<infer U>
? U | ElementBeforeTailingSpreadElement
: never;
13 changes: 13 additions & 0 deletions test-d/last-array-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,16 @@ expectType<2>(lastOf(mixedArray));
expectType<string>(lastOf(['a', 'b', 'c']));
expectType<string | number>(lastOf(['a', 'b', 1]));
expectType<1>(lastOf(['a', 'b', 1] as const));

declare const leadingSpreadTuple: [...string[], object, number];
expectType<number>(lastOf(leadingSpreadTuple));

declare const trailingSpreadTuple1: [string, ...number[]];
expectType<number | string>(lastOf(trailingSpreadTuple1));

declare const trailingSpreadTuple2: [string, boolean, ...number[]];
expectType<number | boolean>(lastOf(trailingSpreadTuple2));

// eslint-disable-next-line @typescript-eslint/array-type
declare const trailingSpreadTuple3: ['foo', true, ...(1 | '2')[]];
expectType<true | 1 | '2'>(lastOf(trailingSpreadTuple3));