Skip to content

Instantly share code, notes, and snippets.

@jcreedcmu
Created March 14, 2018 20:58
Show Gist options
  • Select an option

  • Save jcreedcmu/84ebe50a83b1e4ae50b24c611caddaf1 to your computer and use it in GitHub Desktop.

Select an option

Save jcreedcmu/84ebe50a83b1e4ae50b24c611caddaf1 to your computer and use it in GitHub Desktop.
More fun with conditional types
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