Skip to content

Instantly share code, notes, and snippets.

@tokland
Forked from willfrew/tuples.ts
Last active February 17, 2020 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tokland/c21fa6a7752f82d573c592cb13394ff4 to your computer and use it in GitHub Desktop.
Save tokland/c21fa6a7752f82d573c592cb13394ff4 to your computer and use it in GitHub Desktop.
Fun with tuple types in Typescript 3.0
type Length<T extends any[]> = T["length"];
type Head<T extends any[]> = T[0];
type Tail<T extends any[]> = ((...xs: T) => any) extends (x: any, ...t: infer T) => any ? T : never;
type Last<T extends any[]> = {
0: never;
1: T[0];
">1": Last<Tail<T>>;
}[Length<T> extends 0 ? 0 : Length<T> extends 1 ? 1 : ">1"];
type T1 = [number, string, boolean, string, { a: number }];
type LengthT1 = Length<T1>; // 5
type LastT1 = Last<T1>; // { a: number }
type HeadT1 = Head<T1>; // number
type TailT1 = Tail<T1>; // [string, boolean, string, { a: number }]
// Validations
const lengthT1: LengthT1 = 5;
const lastT1: LastT1 = { a: 1 };
const headT1: HeadT1 = 42;
const tailT1: TailT1 = ["hello", true, "world", { a: 2 }];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment