在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;
- Node.js中的相同命名空间中的每个文件的TypeScript类
- 模块构build失败:错误:AotPlugin被检测到,但是它是一个错误类的实例
- 从TypeScript Firebase Admin SDK初始化失败
- 如何configuration使用从PureScript编译的JavaScript模块的TypeScript项目?
- 在typescript(angular2)应用程序中joinnode_module
- 在打字稿中找不到'autobind-decorator'的声明文件
- 如何将@types的版本与NodeJS Typescript中关联包的版本相关联?
- 通过环境TypeScript公开一个Node.js库
- 找不到模块'ts-node / register'