Skip to content

Commit

Permalink
Fix support for readonly and generic arrays in the LastArrayElement
Browse files Browse the repository at this point in the history
… type (#266)
  • Loading branch information
JounQin committed Sep 17, 2021
1 parent 76c08c2 commit 8f70e88
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
10 changes: 6 additions & 4 deletions source/last-array-element.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ typeof lastOf(array);
@category Template Literals
*/
export type LastArrayElement<ValueType extends readonly unknown[]> =
ValueType extends [infer ElementType]
ValueType extends readonly [infer ElementType]
? ElementType
: ValueType extends [infer _, ...infer Tail]
? LastArrayElement<Tail>
: never;
: ValueType extends readonly [infer _, ...infer Tail]
? LastArrayElement<Tail>
: ValueType extends ReadonlyArray<infer ElementType>
? ElementType
: never;
5 changes: 4 additions & 1 deletion test-d/last-array-element.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import {expectType} from 'tsd';
import {LastArrayElement} from '../index';

declare function lastOf<V extends [any, ...any]>(array: V): LastArrayElement<V>;
declare function lastOf<V extends readonly unknown[]>(array: V): LastArrayElement<V>;
const array: ['foo', 2, 'bar'] = ['foo', 2, 'bar'];
const mixedArray: ['bar', 'foo', 2] = ['bar', 'foo', 2];

expectType<'bar'>(lastOf(array));
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));

0 comments on commit 8f70e88

Please sign in to comment.