Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generic types for pubSub (with solution) #223

Open
1 of 4 tasks
Akxe opened this issue Apr 4, 2020 · 0 comments
Open
1 of 4 tasks

Generic types for pubSub (with solution) #223

Akxe opened this issue Apr 4, 2020 · 0 comments

Comments

@Akxe
Copy link

Akxe commented Apr 4, 2020

By adding generic to PubSubEngine, a lot of typos and (hard) type lookup can be prevented.

  • has-reproduction
  • feature
  • blocking
  • good first issue

Here is an example of the type definition to look like in the end.

const pubSub = new PubSub<{
	commentsChanged: Comment[],
	postsChanged: Post[],
}>();

//  `pubSub.publish` will now only accept keys listed in generic type of `pubSub` instance 
// **The type must match too!**
pubSub.publish('commentAdded', { commentAdded: new Comment( /*...*/ )] });

Here is what needed to be done. (I looked that there is an ongoing change to rename asyncIterator and didn't felt like dealing with it.)

pubsub-engine.d.ts

export type PubSubEngineGeneric = {
    [key: string]: any;
}

export declare abstract class PubSubEngine<T extends PubSubEngineGeneric> {
    abstract publish<key extends keyof T>(triggerName: key, payload: { [key]: T[key] }): Promise<void>;
    abstract subscribe<key extends keyof T>(triggerName: key, onMessage: Function, options: Object): Promise<number>;
    abstract unsubscribe(subId: number): any;
    asyncIterator<key extends keyof T>(triggers: key | key[]): AsyncIterator<T[key]>;
}

pubsub.d.ts

/// <reference types="node" />
import { EventEmitter } from 'events';
import { PubSubEngine, PubSubEngineGeneric } from './pubsub-engine';
export interface PubSubOptions {
    eventEmitter?: EventEmitter;
}
export declare class PubSub<T extends PubSubEngineGeneric = any> extends PubSubEngine<T> {
    protected ee: EventEmitter;
    private subscriptions;
    private subIdCounter;
    constructor(options?: PubSubOptions);
    get<key extends keyof T>(prop: key): T[key];
    publish<key extends keyof T>(triggerName: key, payload: { [key]: T[key] }): Promise<void>;
    subscribe(triggerName: string, onMessage: (...args: any[]) => void): Promise<number>;
    unsubscribe(subId: number): void;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant