Last active
September 12, 2018 11:55
-
-
Save bloadvenro/acd68b5cb14458031bf05bb7b24b8856 to your computer and use it in GitHub Desktop.
Typescript recursive switch type
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
type Switch<T, CaseList extends CaseLike[], Default> = { | |
case: ((...caseList: CaseList) => any) extends ((current: infer C, ...rest: infer R) => any) | |
? C extends CaseLike // we must ensure in that to access 'case' property of C | |
? C['case'] extends T | |
? C['then'] | |
: R extends CaseLike[] // we must ensure in that to pass R as the third argument below | |
? Switch<T, R, Default> | |
: never // this branch will never occur: R is always CaseLike[] | |
: 'this branch will never occur: C is always CaseLike' | |
: never; // this branch will never occur because of condition below | |
default: Default; | |
}[CaseList extends [any, ...any[]] ? 'case' : 'default']; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment