-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Description
15 - Last of Array
Accessing the values of an array is an essential skill. This one seems a little tricky at first, but before long the solution should become more clear. It seems pedantic, but it's going to come up again: trust me.
🎥 Video Explanation
🔢 Code
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
type A1 = Last<[3, 2, 1]>;
type B1 = 1;
type C1 = Expect<Equal<A1, B1>>;
type A2 = Last<[() => 123, { a: string }]>;
type B2 = { a: string };
type C2 = Expect<Equal<A2, B2>>;
type A3 = Last<[]>;
type B3 = never;
type C3 = Expect<Equal<A3, B3>>;
// ============= Your Code Here =============
type Last<T extends unknown[]> =
// also can do `...infer _`
T extends [...any, infer Tail]
? Tail
: never
;
type Last<T extends unknown[]> =
[never, ...T][T["length"]]
;➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
No labels