Skip to content

Instantly share code, notes, and snippets.

@jcreedcmu
Created March 13, 2018 20:25
Show Gist options
  • Select an option

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

Select an option

Save jcreedcmu/b7c0232ecad88f02149850f94838d172 to your computer and use it in GitHub Desktop.
Fun things to do with Typescript 2.8
type Union =
{ type: 'A', a: string } |
{ type: 'B', b: number }
type FilterType<T, K> = (T extends { type: K } ? T : never);
type RemoveType<T, K> = (T extends K ? never : T);
type MappedUnion = {[P in Union['type']]: RemoveTypeFromRecord<FilterType<Union, P>, 'type'>};
type MappedUnionTarget = {
A: { a: string }
B: { b: number }
}
type RemoveType<T, K> = (T extends K ? never : T);
type RemoveTypeFromRecord<T, K> = {[L in RemoveType<keyof T, K>]: T[L]}
type Test = RemoveTypeFromRecord<{A: string, B: number, C: boolean[]}, 'C'>;
type TestTarget = {A: string, B: number};
function cvt3(x : Test): TestTarget {
return x;
}
function cvt4(x : TestTarget): Test {
return x;
}
// const z: RemoveTypeFromRecord<{type: 'A', a: string}, 'type'> = {'a': 'tadf'};
// type Blerp = {[K in keyof MappedUnionTarget]: RemoveType<MappedUnionTarget[K]>};
function cvt1(x: MappedUnion): MappedUnionTarget {
return x;
}
function cvt2(x: MappedUnionTarget): MappedUnion {
return x;
}
const v: MappedUnion = {
'A': { a: "d"},
'B': { b: 3},
}
@jcreedcmu
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment