nehalist
nehalist

Reputation: 1496

Callback interfaces

I'd like to define the exact paramters of a callback function, in my specific case for registering middleware. Middleware takes three arguments (req, req and next), hence my interface looks like this:

interface MiddlewareInterface {
  (req, res, next): void
}

The simplified class for it:

class Application {
    protected app;

    registerMiddleware(callback: MiddlewareInterface): void {
        this.app.use(callback);
    }
}

Sadly this is still allowed

registerMiddleware(() => { /* ... */ });

But why?

Upvotes: 0

Views: 67

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164287

Because in javascript you can choose to ignore the arguments.

For example, let's say that I want to add a middleware that will throw if it's reached:

registerMiddleware((req, res, next) => {
    throw new Error("Should not have reached me!");
});

As the args are not used there's no need to them, this works just fine:

registerMiddleware(() => {
    throw new Error("Should not have reached me!");
});

Upvotes: 1

Related Questions