Skip to content

Instantly share code, notes, and snippets.

@fersilva16
Created May 29, 2022 17:43
Show Gist options
  • Save fersilva16/0299d588432b6ddae8c739b7993b8fe4 to your computer and use it in GitHub Desktop.
Save fersilva16/0299d588432b6ddae8c739b7993b8fe4 to your computer and use it in GitHub Desktop.
Taking the last element in an array in TypeScript type system.
// Or just get the last element!
type GetLast<XS extends unknown[]>
= [never, ...XS][XS['length']];
// => never
type Empty = TakeLast<[]>;
// => 1
type OneEl = TakeLast<[1]>;
// => 5
type MultEls = TakeLast<[1, 2, 3, 4, 5]>
// Util for asserting types
export type Assert<X, T> = X extends T ? X : never;
// Take the last element of a tuple
// and returning the rest
type TakeLast<XS extends unknown[]> = XS extends [infer X, ...infer YS]
? YS extends []
? [[], X]
: TakeLast<YS> extends [infer ZS, infer R]
? [[X, ...Assert<ZS, unknown[]>], R]
: never
: never;
// => never
type Empty = TakeLast<[]>;
// => [[], 1]
type OneEl = TakeLast<[1]>;
// => [[1, 2, 3, 4], 5]
type MultEls = TakeLast<[1, 2, 3, 4, 5]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment