Skip to content

Instantly share code, notes, and snippets.

@jfet97
Last active April 20, 2022 17:29
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 jfet97/6a68169fb5d4f93e79c45d1ed6643b97 to your computer and use it in GitHub Desktop.
Save jfet97/6a68169fb5d4f93e79c45d1ed6643b97 to your computer and use it in GitHub Desktop.
Valid numerical index tuple
type IndexesKeysOfTuple<T extends any[]> = Exclude<
keyof T & string,
keyof any[]
>;
type NumberToString<N extends number | bigint> = `${N}`;
type ValidIndex<T extends any[], I extends number> = any[] extends T
? number // T is an array but not a tuple type
: NumberToString<I> extends IndexesKeysOfTuple<T>
? I
: never;
function fn<T extends any[], I extends number>(
t: readonly [...T],
i: ValidIndex<T, I>
): void {
// ...
}
fn(["hi", "how", "are", "you", "?"] as const, 2);
fn(["hi", "how", "are", "you", "?"], 5); // error
fn(["hi", "how", "are", "you", "?"] as Array<string>, 2);
fn(["hi", "how", "are", "you", "?"] as Array<string>, 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment