How can I apply an interface to an anonymous callback function in typescript
I have an interface similar to this
interface CallBackHandler{
(err: Error, response: {statusCode: number, body: object}):void
}
and I want to apply this 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 message that the function should return something if the return type is not invalid when i add the interface
(err, response): CallBackHandler => {
this.handleResponse(err, response, resolve, reject);
}
What is the correct way to use this interface?
+3
source to share
2 answers
If request()
already has a type signature:
function request(options, callback: CallBackHandler) {
...
}
Then you don't need to do anything, as the callback you provide will be type checked appropriately.
If this function does not already have such a type signature, and you want to manually reverse the callback to CallBackHandler
, then you will need to wrap the callback function in parentheses and apply that expression like so:
request({
...etc
}, ((err, response) => {
this.handleResponse(err, response, resolve, reject);
}) as CallBackHandler);
+1
source to share