Created
March 14, 2018 20:58
-
-
Save jcreedcmu/84ebe50a83b1e4ae50b24c611caddaf1 to your computer and use it in GitHub Desktop.
More fun with conditional types
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 Rec = { | |
| 'text': string, | |
| 'bool': boolean | |
| }; | |
| type Un = | |
| | {t: 'text', v: string} | |
| | {t: 'bool', v: boolean}; | |
| type Datum<K, V> = { t: K, v: V }; | |
| type FromKeys<T, U> = T extends keyof U ? Datum<T, U[T]> : never; | |
| type UnOfRec<T> = FromKeys<keyof T, T>; | |
| type FilterType<T extends {v: any}, K> = (T extends { t: K } ? T['v'] : never); | |
| type RecOfUn<T extends {t: string, v: any}> = {[P in T['t']]: FilterType<T, P>}; | |
| // UnOfRec<Rec> = Un | |
| function eq1(x: UnOfRec<Rec>): Un { return x } | |
| function eq2(x: Un): UnOfRec<Rec> { return x } | |
| // RecOfUn<Un> = Rec | |
| function eq3(x: RecOfUn<Un>): Rec { return x } | |
| function eq4(x: Rec): RecOfUn<Un> { return x } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment