【问题标题】:Using an array of callback functions in express in typescript在打字稿中使用express中的回调函数数组
【发布时间】:2015-07-12 00:44:18
【问题描述】:

我正在尝试在打字稿中重新创建 express routing example

我有……

/// <reference path='Scripts/typings/express/express.d.ts' />
import express = require('express');
var app = express();

var cb0: express.RequestHandler = function (req, res, next) {
    console.log('CB0');
   next();
}

var cb1: express.RequestHandler = function (req, res, next) {
    console.log('CB1');
    next();
}

var cb2: express.RequestHandler = function (req, res) {
    res.send('Hello from C!');
}

var arr: express.RequestHandler[] = [cb0, cb1, cb2];

app.get('/example/c', arr);

打字稿编译器向我抛出的第一个错误是 '/example/c'Argument of type 'string' is not assignable to parameter of type 'RegExp'... 很奇怪,因为在 express.d.ts 中,该函数被定义为允许字符串,正则表达式...但是,好吧,我把它改成new RegExp('/example/c')

然后它向我抛出错误Argument of type 'RequestHandler[]' is not assignable to parameter of type 'RequestHandler'.。也很奇怪,因为express.d.ts 文件有定义为允许数组的方法。

这里的打字稿很新,这些是一些神秘的错误消息......

【问题讨论】:

标签: javascript node.js express typescript


【解决方案1】:

把你的sn-p的最后一行改成这样,应该没问题:

app.get('/example/c', cb0, cb1, cb2);

您不能将 RequestHandlers 数组传递给第二个参数...。它是 Typescript 中称为“rest”参数的一种特殊类型的参数,类似于 C# 中的“params”。

【讨论】:

  • 谢谢!这很有意义。
猜你喜欢
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 2018-04-22
  • 2016-11-27
  • 2017-09-15
  • 1970-01-01
相关资源
最近更新 更多