简体   繁体   中英

How can i apply an interface to an anonymous callback function in typescript

I have an interface that looks like this

interface CallBackHandler{
 (err: Error, response: {statusCode: number, body: object}):void
}

and i want to apply that interface to the callback of this

    request({
    url: url,
    method: "GET",
    withCredentials: false,
    json: true,
    headers: headers
  }, (err, response) => {
    this.handleResponse(err, response, resolve, reject);
  });

but im getting a error saying the function must return something if the return type is not void when i add the interface

(err, response): CallBackHandler => {
    this.handleResponse(err, response, resolve, reject);
  }

what is the correct way to apply this interface?

If request() already has the type signature:

function request(options, callback: CallBackHandler) {
   ...
}

Then you shouldn't need to do anything, as the callback you provide will be type-checked accordingly.

If that function doesn't already have that type signature, and you want to manually cast your callback to CallBackHandler , then you will need to wrap the callback function in parentheses and cast that expression, like so:

request({
    ...etc
}, ((err, response) => {
    this.handleResponse(err, response, resolve, reject);
}) as CallBackHandler);

You can have something like

request({
  url: url,
  method: "GET",
  withCredentials: false,
  json: true,
  headers: headers
}, (err: Error, response: {statusCode: number, body: object}) => {
  this.handleResponse(err, response, resolve, reject);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM