如何重构类型注释?

时间:2012-10-04 22:51:03

标签: typescript

让我们假设我正在定义一个模块,我有一些像这样的函数定义:

export function bodyParser(options?:any): 
  (req: ExpressServerRequest, res: ExpressServerResponse, next) =>void;
export function errorHandler(opts?:any): 
  (req: ExpressServerRequest, res: ExpressServerResponse, next) =>void;
export function methodOverride(): 
  (req: ExpressServerRequest, res: ExpressServerResponse, next) =>void;
export function favicon(url: string, opts? ): 
  (req: ExpressServerRequest, res: ExpressServerResponse, next) =>void;
export function logger(type: string, opts? ): 
  (req: ExpressServerRequest, res: ExpressServerResponse, next) =>void;

我反复使用这种返回类型注释:

(req: ExpressServerRequest, res: ExpressServerResponse, next) =>void

有没有办法定义该类型,为其指定名称,只引用名称而不是重复同样的事情?

1 个答案:

答案 0 :(得分:6)

是的!您可以使用带有呼叫签名的接口:

interface MyCallSignature {
    (req: ExpressServerRequest, res: ExpressServerResponse, next): void;
}

现在您可以使用它:

export function bodyParser(options?: any): MyCallSignature