Oguzhan Oguzhan - 3 months ago 13
TypeScript Question

Type casting on arrow functions

I would like to cast callback function type to another type.
For example, with express.

//definitions.ts
interface ExtendedRequest extends express.Request{
user:IUser;
}
interface ExtendedRequestHandler{
(req:ExtendedRequest, res:express.Response, next:express.NextFunction):any;
}
//app.ts
import * as D from './definitions';
...
// if i use with 'function' keyword it works
app.post('/login', <D.ExtendedRequestHandler>function(req,res){/*..*/});
//but if i try casting on anonymous arrow function, it doesnt work,
//i am getting error ',' expected
app.post('/login', <D.ExtendedRequestHandler>(req,res)=>{/*..*/});


Is there a way to apply the type casting on arrow functions?

Thanks..

Answer

TypeScript thinks you're trying to write a generic arrow function when written that way. You just need to add some parentheses to clear up the confusion:

app.post('/login', <D.ExtendedRequestHandler>((req,res)=>{/*..*/}));