在TypeScript中,我该如何实现一个接口(a:type,b:type):any?

具体来说,我试图设置服务器双面打字稿的快递。

公开的接口之一是RequestHandler,具有以下结构:

// express-serve-static-core/index.d.ts declare module "express-serve-static-core" { ... interface RequestHandler { (req: Request, res: Response, next: NextFunction): any; } } 

我写了下面的课:

 import * as express from "express"; class PageNotFound implements express.RequestHandler { constructor (req: express.Request, res: express.Response, next: express.NextFunction) { let viewFilePath: string = "404"; let statusCode: number = 404; let result: Object = { status: statusCode, }; res.status(statusCode); res.render(viewFilePath, {}, function (err: Error, html: string): void { if (err) { res.status(statusCode).json(result); } res.send(html); }); } } 

但是,这会引发错误:

error TS2345: Argument of type 'typeof PageNotFound' is not assignable to parameter of type 'RequestHandler'. Type 'typeof PageNotFound' provides no match for the signature '(req: Request, res: Response, next: NextFunction): any'

有什么build议吗? 我不确定我做错了什么。

RequestHandler是一个接口,用一个呼叫签名来指定某些类不能实现的东西。 你想要一个常规的function:

 function pageNotFound(req: express.Request, res: express.Response, next: express.NextFunction) { ... } 

如果接口在方法签名之前有new ,它将定义类的构造函数的形状,但事实并非如此。

另一种思考的方式是:当你使用一个类时,你定义了一个函数,必须用new来调用。 Express会打电话给“新的PageNotFound(…)”还是叫“pageNotFound(…)”?

Ryan Cavanaugh是TypeScript开发人员之一,他在这里提到:

更正式地说,一个实现接口的类是什么类实例的合同… – – Ryan Cavanaugh 11年12月15日在23:57

你想保持简单,类是用于多次使用的对象。 模块express为您提供具有正确属性的路由器对象。

 import * as express from 'express'; const router = express.Router(); router.get('/', (req: express.Request, res: express.Response, next: express.NextFunction) => { res.render('index', { title: 'Express' }) }); export = router;