ts-node: Type declaration merging doesn't work

I’ve tried to extend the standard Express Request interface, VSCode is picking up the declaration, but when I run ts-node index.ts I get :

/Users/vladr/.nvm/versions/node/v10.6.0/lib/node_modules/ts-node/src/index.ts:261
    return new TSError(diagnosticText, diagnosticCodes)
           ^
TSError: ⨯ Unable to compile TypeScript:
index.ts(6,9): error TS2339: Property 'addedProperty' does not exist on type 'Request'.
index.ts(7,21): error TS2339: Property 'addedProperty' does not exist on type 'Request'.

However running tsc works fine. Also this is only a problem with ts-node@7, if I add TS_NODE_FILES=true it works as expected.

Here is a test repo to reporoduce the error: https://github.com/vladrmnv/ts-node-broken-declaration-merging

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 6
  • Comments: 16 (2 by maintainers)

Most upvoted comments

Here is a working example for those who still struggling (like I was for past few hours):

@types/express/index.d.ts: (MUST be <module-name>/index.d.ts)

declare namespace Express { // MUST be namespace, and not declare module "Express" { 
  export interface Request {
    Bla: string;
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2016",
    "typeRoots" : [
      "@types", // custom merged types MUST be first in a list
      "node_modules/@types",
    ]
  }
}

If you are using “paths” in tsconfig.json you also MUST provide library mapping like that:

    "baseUrl": ".",
    "paths": {
      ...
      "express": ["@types/*"]
    }

Afterwards I was able to run tsc -p ., ts-node index.ts and ts-node-dev index.ts successfully.

Thanks to this comment by @blakeembrey, I got my declaration merges working! All you need to do is put "./typings" before "./node_modules/@types".

"typeRoots": ["./typings", "./node_modules/@types"]

@vladrmnv @john-kurkowski did anyone of you figured this out and could post a sample of what needs to be changed? I still don’t get it. How can I add a prop to the express Request type declaration and have declaration merging working? I only get it to either pick up the default express declarations or my custom declaration but I don’t get it to merge them.

Having the same issue, this fixed it https://github.com/TypeStrong/ts-node/issues/615#issuecomment-399808213

Basically, add the --files flag to ts-node to the get the pre 7.0.0 behaviour.

ts-node --files src/index.ts

@john-kurkowski yep, tried that, bug how would I merge my custom definition with the existing definitions? Such as in my express example?