Skip to content

Instantly share code, notes, and snippets.

@bloadvenro
Last active September 12, 2018 11:55
Show Gist options
  • Save bloadvenro/acd68b5cb14458031bf05bb7b24b8856 to your computer and use it in GitHub Desktop.
Save bloadvenro/acd68b5cb14458031bf05bb7b24b8856 to your computer and use it in GitHub Desktop.
Typescript recursive switch type
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