Created
September 4, 2019 21:47
-
-
Save webstrand/c9fe4acc4614279a983e7cb612048ad2 to your computer and use it in GitHub Desktop.
Find all of the prefixes of some function type by recursive function
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
/** | |
* Unshift T onto the arguments list of S. | |
*/ | |
type Unshift<S extends (...args: any[]) => any, T> = | |
S extends (...args: infer U) => any ? (arg: T, ...args: U) => any : never; | |
/** | |
* Generate all the prefixes of T, not including | |
* the nullary function nor T itself (unless T variadic). | |
* Return types are not preserved. | |
*/ | |
type Prefixes<T extends (...args: any[]) => any> = { | |
0: () => any, | |
1: T extends (_: infer U, ...args: infer V) => any | |
? Unshift<Prefixes<(...args: V) => any>, U> | ((arg: U) => any) | |
: never, | |
2: T | |
}[ | |
T extends (arg: infer U, ...args: infer V) => any | |
? U[] extends V | |
? 2 | |
: V extends [] | |
? 0 : 1 | |
: 0 | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment