#TypeScript is inferring the return type of a returned function as any

5 messages · Page 1 of 1 (latest)

lyric yew
#

TypeScript is inferring the return type of a returned function as any

hexed rune
#

This usually happens when TypeScript cannot infer the type of a function that returns another function, so it falls back to any. The fix is to explicitly type the return value.

#

.function createHandler() {
return function (req, res) {
return req.body;
};
}

#

function createHandler(): (req: Request, res: Response) => unknown {
return function (req, res) {
return req.body;
};
}

#

type Handler = (req: Request, res: Response) => unknown;

function createHandler(): Handler {
return (req, res) => {
return req.body;
};
}