Skip to content

Instantly share code, notes, and snippets.

@rklaehn
Last active February 23, 2018 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklaehn/91064384d952176f720e028d36bd3f3f to your computer and use it in GitHub Desktop.
Save rklaehn/91064384d952176f720e028d36bd3f3f to your computer and use it in GitHub Desktop.
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))
@rklaehn
Copy link
Author

rklaehn commented Feb 23, 2018

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