Skip to content

Instantly share code, notes, and snippets.

@hasparus
Last active May 9, 2019 17:06
Show Gist options
  • Save hasparus/a97f0d05b41893753586927afd90a647 to your computer and use it in GitHub Desktop.
Save hasparus/a97f0d05b41893753586927afd90a647 to your computer and use it in GitHub Desktop.
Typed PubSub subscribe
import { PubSub } from 'graphql-subscriptions';
type PubSubAction = [typeof MESSAGE_ADDED, MessageAddedPayload] | ['foo', 121];
type UnionToIntersection<U> =
(U extends any ? (k: U) => void : never) extends
((k: infer I) => void) ? I : never;
type PairsToRecord<Pair extends [string, any]> =
Pair extends [infer T1, infer T2]
? { [P in Extract<T1, string>]: T2 }
: never;
type X = PairsToRecord<PubSubAction>;
type Y = UnionToIntersection<X>;
const pubsub = new PubSub() as Assign<
PubSub,
{
publish(...args: PubSubAction): Promise<void>;
// subscribe(
// triggerName: typeof MESSAGE_ADDED,
// onMessage: (payload: MessageAddedPayload) => void
// ): Promise<number>;
subscribe<TriggerName extends keyof Y>(
triggerName: TriggerName,
onMessage: (payload: Y[TriggerName]) => void
): Promise<number>
}
>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment