在Typescript中,如何在声明函数之前使用它?

时间:2019-07-18 20:43:01

标签: typescript

我想声明一个函数,将其作为处理程序传递,然后再对其进行定义,我的代码如下:

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) => { ... };

在第2行传递函数时出现此错误,我在做什么错?

  

TS2448:在其作用域之前使用的块作用域变量'authenticateHandler'   声明

1 个答案:

答案 0 :(得分:1)

要么在使用常量函数之前声明它(如警告所示)。

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);

或将其定义为函数:

function authenticateHandler(req: Restify.Request, res: Restify.Response) => { ... };