Last active
February 23, 2018 23:15
-
-
Save rklaehn/91064384d952176f720e028d36bd3f3f to your computer and use it in GitHub Desktop.
This file contains 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
const enum Test { a = 'a' } | |
type Protocol = { | |
foo: { x: string }; | |
bar: { y: number }; | |
} | |
type WithTag<T> = { | |
[TKey in keyof T]: { type: TKey } & T[TKey] | |
} | |
type ToDiscriminatedUnion<P> = WithTag<P>[keyof P] | |
type Constructor<T> = { | |
[P in keyof T]: (value: T[P]) => { type: P } & T[P] | |
} | |
const Constructor: <P>() => Constructor<P> = <P>() => | |
new Proxy<Constructor<P>>({} as any, { | |
get: (target, type) => (args) => | |
({...args, type}) | |
}) | |
type Constructor2<T> = { | |
[P in keyof T]: (value: T[P]) => ToDiscriminatedUnion<T> | |
} | |
const Constructor2: <P>() => Constructor2<P> = <P>() => | |
new Proxy<Constructor2<P>>({} as any, { | |
get: (target, type) => (args) => | |
({...args, type}) | |
}) | |
const Protocol = Constructor2<Protocol>() | |
const res = Protocol.foo({ x: 'x' }) | |
alert(JSON.stringify(res)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
link