Last active
April 20, 2022 17:29
-
-
Save jfet97/6a68169fb5d4f93e79c45d1ed6643b97 to your computer and use it in GitHub Desktop.
Valid numerical index tuple
This file contains hidden or 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
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