ts-node: Can't extend express Request type
// ./typings/express/index.d.ts
declare namespace Express {
export interface Request {
token?: string
}
}
Example usage:
import * as express from 'express'
(req: express.Request, res: express.Response, next: express.NextFunction) => {
const foo = req.token
}
It does work if I compile directly (tsc -p .
), it does work in Visual Code, but when I try to run with ts-node
I always get:
error TS2339: Property ‘token’ does not exist on type ‘Request’.
Any idea how can I make it work with ts-node?
Versions: ts-node@7.0.1
typescript@3.0.1
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 5
- Comments: 25 (9 by maintainers)
Please see the README and CHANGELOG, and possibly search past issues to find why it was changed.
Thanks to this comment by @blakeembrey, I got my declaration merges working! All you need to do is put
"./typings"
before"./node_modules/@types"
.To help anyone who is just looking for something else to try here is what worked for me when trying to extend ExpressJS’ Request. I had to have tried more than a dozen things before getting this to work:
The following worked for me:
And then run
As ts-node does not use files because of slows startup time, we need to tell it explicitly. Hence ‘–files’ is necessary here.
With
--files
ints-node
command local declaration files are recognized. Example command:ts-node --files src/index.ts
Can you guys @3mard @blakeembrey tell WHY this works? I would like understand more 😃 Also is this the best solution for this problem or is it only a workaround?
Same. I can’t make it work. Neither solution helps. Yours is an ugly hack but works for sure.
My problem is that VSCode recognizes it, and all is green. But when I try to run it with ts-node, it gives the error.
@brunolm @henrikra I created this repo example https://github.com/3mard/ts-node-example for extending express request
This worked for me:
As this is confusing a lot of people to get right, I’d suggest setting up a working example in the docs
@brunolm That wouldn’t work because it’d just discover the first one, not all of them. You can always use the
/// <reference />
directive to resolve the one you specifically want to extend (and put yourtypeRoots
first, otherwise you’re just resolving@types
anyway - it may even work by just switching the order oftypeRoots
above and no need forreference
since one is a module and the other definition is global).Works for me… I add “–files” flag in the run command “ts-node --files index.ts”, and create express.d.ts with the follow content.
declare namespace Express { export interface Request { user_id: number; } }
You need to import or export something to indicate that the file is a module. If you are not importing anything then simply add
in that file, then the error should be gone.
VSCode gives me: