cf.completefrontend

Write the codeMedium

Add overloads to on(event, handler) so each event's handler gets the right parameter type.

A small event bus has three events: message carries a string, progress a number, and close nothing. Right now every handler's parameter is any, and any event name is accepted. Add overload signatures so each handler is typed and an unknown event name is an error. Keep the implementation as it is.

Write this
type Handler = (payload?: any) => void;const handlers = new Map<string, Handler[]>(); function on(event: string, handler: Handler) {  handlers.set(event, [...(handlers.get(event) ?? []), handler]);} function emit(event: string, payload?: unknown) {  for (const handler of handlers.get(event) ?? []) handler(payload);} // on("message", (text) => console.log(text.toUpperCase())); // text: string// on("progress", (percent) => console.log(percent.toFixed(0))); // percent: number// on("close", () => console.log("closed"));// on("resize", () => {}); // should be a type error

Solve it in the editor

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…