Trying to establish type information for event listeners by using generics on the .on()
function.
type Name = "error" | "connected";
type Callback = {
error: (err: Error) => void,
connected: (err: number) => void,
};
function on<T extends Name>(eventName: T, callback: Callback[T]): void { }
on("error", (err) => err.stack);
on("connected", (err) => err.stack);
Expected an error for the connected
event due to the attempt to use a number
as an Error
, but received no type hinting for the callback functions.
If all function definitions in Callback
match, functionality starts to work. For example:
type Callback = {
error: (err: Error) => void,
connected: (err: Error) => void,
};
View the GIF demonstrating the issue in VS Code:
https://i.sstatic.net/nIxu1.gif
Is there an error in my approach?