Skip to content

Keep default any event type #7

@Niels-Be

Description

@Niels-Be

In my use case I am extending a library which has some static event names and some are dynamic generated.
So I would like to have some events typed but keep the default any emitter.
I adapted your library for this and wanted the share the code.
I think this is a general use case and would fit in this library.
So if you like it you could export it as an additional interface something like LooselyTypedEmitter<L>.
Note that this will prevent strict type checking, so it is not a replacement.

declare type DefaultFunction = (...args: any[]) => any;
declare type ListenerSignature<L> = {
    [E in keyof L]: DefaultFunction;
};

declare type DefaultListener = {
    [k: string]: DefaultFunction;
};

export class LooselyTypedEmitter<L extends ListenerSignature<L> = DefaultListener> {
    static defaultMaxListeners: number;
    addListener<U extends keyof L>(event: U, listener: L[U]): this;
    addListener(event: string, listener: DefaultFunction): this;
    prependListener<U extends keyof L>(event: U, listener: L[U]): this;
    prependListener(event: string, listener: DefaultFunction): this;
    prependOnceListener<U extends keyof L>(event: U, listener: L[U]): this;
    prependOnceListener(event: string, listener: DefaultFunction): this;
    removeListener<U extends keyof L>(event: U, listener: L[U]): this;
    removeListener(event: string, listener: DefaultFunction): this;
    removeAllListeners(event?: keyof L): this;
    removeAllListeners(event?: string): this;
    once<U extends keyof L>(event: U, listener: L[U]): this;
    once(event: string, listener: DefaultFunction): this;
    on<U extends keyof L>(event: U, listener: L[U]): this;
    on(event: string, listener: DefaultFunction): this;
    off<U extends keyof L>(event: U, listener: L[U]): this;
    off(event: string, listener: DefaultFunction): this;
    emit<U extends keyof L>(event: U, ...args: Parameters<L[U]>): boolean;
    emit(event: string, ...args: any[]): boolean;
    eventNames<U extends keyof L>(): U[];
    listenerCount(type: keyof L): number;
    listenerCount(type: string): number;
    listeners<U extends keyof L>(type: U): L[U][];
    listeners(type: string): DefaultFunction[];
    rawListeners<U extends keyof L>(type: U): L[U][];
    rawListeners(type: string): DefaultFunction[];
    getMaxListeners(): number;
    setMaxListeners(n: number): this;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions