2

I'm trying to re-create the express routing example in typescript

I have...

/// <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);

The first error the typescript compiler throws at me is for '/example/c' saying Argument of type 'string' is not assignable to parameter of type 'RegExp'... odd, since in express.d.ts the function is defined as allowing a string, or a regex... but, ok, I change it to new RegExp('/example/c')

Then it throws the error Argument of type 'RequestHandler[]' is not assignable to parameter of type 'RequestHandler'. at me. Also odd, since the express.d.ts file has the method defined as allowing an array.

Very new to typescript here, and these are some cryptic error messages...

1

1 Answer 1

2

Change the last line of your snippet to this, and you should be fine:

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

You can't pass in an array of RequestHandlers to that second parameter .... it is a special type of parameter in Typescript called "rest" parameter, analogous to "params" in C#.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That makes a lot of sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.