Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Typescript, how to use a function before it's declared?

Tags:

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

like image 274
Bill Software Engineer Avatar asked Jul 18 '19 20:07

Bill Software Engineer


People also ask

Can I call a function before it is declared?

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.

How do you pass a function in TypeScript?

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.

Can we use function in TypeScript?

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.

What does () void mean TypeScript?

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.


1 Answers

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) => { ... };
like image 193
Igor Soloydenko Avatar answered Nov 15 '22 06:11

Igor Soloydenko