In an effort to reduce the cognitive load on my aging gray matter, I'm providing custom overloads for specific events in an event emitter.
// default signature
function on(event: string | symbol, listener: (...args: any[]) => void): void;
// custom signatures
function on(event: "error", listener: (error: string, code: number) => void): void;
function on(event: "data", listener: (text: string) => void): void;
function on(event: "chunk", listener: (text: string) => void): void;
function on(event: "complete" | "done", listener: (id: number) => void): void;
// most general signature
function on(event: any, listener: (...args: any[]) => void) {
// ...
}
// correctly resolve data as 'string'
on("data", (data) => {});
on("chunk", (data) => {});
// incorrectly resolves id as any from default signature
on("complete", (id) => {});
Per the TypeScript docs, I've ordered general overloads after specific overloads.
My question is; why does the union type ("complete" | "done") not work as expected but separating them ("data" and "chunk") does?