Skip to content

Instantly share code, notes, and snippets.

@jtbandes
Created October 13, 2022 18:47
Show Gist options
  • Save jtbandes/0fb642d7affba7a4ec37ac861b6dd183 to your computer and use it in GitHub Desktop.
Save jtbandes/0fb642d7affba7a4ec37ac861b6dd183 to your computer and use it in GitHub Desktop.
TypeScript tuple types using non-type generic parameters
type Ten<T extends any[]> = [...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T]
type Tuple<T, N extends number> =
N extends 0 ? [] :
N extends 1 ? [T] :
N extends 2 ? [T,T] :
N extends 3 ? [T,T,T] :
N extends 4 ? [T,T,T,T] :
N extends 5 ? [T,T,T,T,T] :
N extends 6 ? [T,T,T,T,T,T] :
N extends 7 ? [T,T,T,T,T,T,T] :
N extends 8 ? [T,T,T,T,T,T,T,T] :
N extends 9 ? [T,T,T,T,T,T,T,T,T] :
`${N}` extends `${infer Rest extends number}0` ? [...Ten<Tuple<T, Rest>>] :
`${N}` extends `${infer Rest extends number}1` ? [...Ten<Tuple<T, Rest>>, ...Tuple<T, 1>] :
`${N}` extends `${infer Rest extends number}2` ? [...Ten<Tuple<T, Rest>>, ...Tuple<T, 2>] :
`${N}` extends `${infer Rest extends number}3` ? [...Ten<Tuple<T, Rest>>, ...Tuple<T, 3>] :
`${N}` extends `${infer Rest extends number}4` ? [...Ten<Tuple<T, Rest>>, ...Tuple<T, 4>] :
`${N}` extends `${infer Rest extends number}5` ? [...Ten<Tuple<T, Rest>>, ...Tuple<T, 5>] :
`${N}` extends `${infer Rest extends number}6` ? [...Ten<Tuple<T, Rest>>, ...Tuple<T, 6>] :
`${N}` extends `${infer Rest extends number}7` ? [...Ten<Tuple<T, Rest>>, ...Tuple<T, 7>] :
`${N}` extends `${infer Rest extends number}8` ? [...Ten<Tuple<T, Rest>>, ...Tuple<T, 8>] :
`${N}` extends `${infer Rest extends number}9` ? [...Ten<Tuple<T, Rest>>, ...Tuple<T, 9>] :
never;
type Mat4 = Tuple<number, 16>
type X = Tuple<number, 101>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment