Created
May 29, 2022 17:43
-
-
Save fersilva16/0299d588432b6ddae8c739b7993b8fe4 to your computer and use it in GitHub Desktop.
Taking the last element in an array in TypeScript type system.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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]> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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