2016-04-22 6 views
2

具体的には、私はexpressのためのサーバ側のtypescriptコンパイルを設定しようとしています。TypeScriptでは、(a:type、b:type):anyのインターフェイスを実装するにはどうすればいいですか?

曝さインターフェイスの1つが、以下の構造を持つの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'

何か提案がありますか?私は何が間違っているのか分かりません。

答えて

2

RequestHandlerは、コールシグネチャで何かを指定しているクラスです。このクラスは実装できません。あなたは、通常の関数たい:

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

インターフェースはメソッドシグネチャの前でnewを持っていた場合、それはあなたのクラスのコンストラクタの形状を定義することになるが、それはそうではありません。

これについてもう1つ考えてみましょう。クラスを使用するときは、newで呼び出す必要がある関数を定義しています。 Expressは "new PageNotFound(...)"を呼び出すか、 "pageNotFound(...)"を呼び出していますか?ライアン・キャバノー、活字体の開発者の一人として

、それをhereを置く:

More formally, a class implementing an interface is a contract on what an instance of the class has... – Ryan Cavanaugh Nov 15 '12 at 23:57

+0

これは正しいです。また、型定義 ':void'と' 'strict strict ';'を追加しました。これは、tslintが不平を言うためです。ありがとう、アラン! – Alexander

0

あなたは、単純な、それを維持したい、クラスが複数回使用されるオブジェクトのためのものです。モジュール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; 
関連する問題