I want to declare a function, pass it as a handler, then define it afterward, my code is like this:
type authenticateHandler = (req: Restify.Request, res: Restify.Response) => any;
server.post("/authentication", authenticateHandler);
server.post("/v1/authentication", authenticateHandler);
const authenticateHandler: authenticateHandler = (req: Restify.Request, res: Restify.Response) => { ... };
I am getting this error when passing the function on line 2, what am I doing wrong?
TS2448: Block-scoped variable 'authenticateHandler' used before its declaration
Hoisting. With JavaScript functions, it is possible to call functions before actually writing the code for the function statement and they give a defined output. This property is called hoisting. Hoisting is the ability of a function to be invoked at the top of the script before it is declared.
Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.
Creating and using functions is a fundamental aspect of any programming language, and TypeScript is no different. TypeScript fully supports the existing JavaScript syntax for functions, while also adding type information and function overloading as new features.
The syntax (a: string) => void means “a function with one parameter, named a , of type string, that doesn't have a return value”. Just like with function declarations, if a parameter type isn't specified, it's implicitly any . Note that the parameter name is required.
Either declare your constant function before it's used (as the warning suggests).
type AuthenticateHandler = (req: Restify.Request, res: Restify.Response) => any;
const authenticateHandler: AuthenticateHandler = (req: Restify.Request, res: Restify.Response) => { ... };
server.post("/authentication", authenticateHandler);
server.post("/v1/authentication", authenticateHandler);
Or define it as a function:
function authenticateHandler(req: Restify.Request, res: Restify.Response) => { ... };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With