Created
March 13, 2018 20:25
-
-
Save jcreedcmu/b7c0232ecad88f02149850f94838d172 to your computer and use it in GitHub Desktop.
Fun things to do with Typescript 2.8
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 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}, | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Related to https://stackoverflow.com/questions/46745785/transform-union-into-a-map/49263466