1

I have been making a webpage for the past two days and I have chosen to use TypeScript.

I have chosen Express.js as the web server, and I have used Express in the past so I know about Express.

I saw that TypeScript looks highly at each property and what properties have, and I have a problem with this because the property "user" is not set by default and I want to use it to save the decoded user session.

After searching online, I found this:

declare module "express" { // declare module "express-serve-static-core"
  export interface Request {
    user: any
  }
}

from this post: Typescript Error: Property 'user' does not exist on type 'Request'

I pasted that into a file and it works well but I have two problems:

  1. I don't know why it works. I don't require the file but however this works, the unique that I made is to require it this in typeroots inside tsconfig.json but executing with ts-node. I don't know if it has any effect (in fact, Visual Studio Code does not throw an error but ts-node does).
  2. I want to give user the type Session, so I imported Session into the file, but now Visual Studio Code tells me that is not in the User property.
leewz
  • 3,201
  • 1
  • 18
  • 38
  • To answer question #2, I'll need to see the corresponding version of the code you tried and the exact text of the error message. – Matt McCutchen Sep 13 '18 at 23:59

2 Answers2

1

module - is a global namespace for types. Docs .

A namespace is a way to logically group related code. This is inbuilt into TypeScript unlike in JavaScript where variables declarations go into a global scope and if multiple JavaScript files are used within same project there will be possibility of overwriting or misconstruing the same variables, which will lead to the “global namespace pollution problem” in JavaScript.

Source

It's better to npm install --save @types/express as it has better types coverage.

Buggy
  • 3,539
  • 1
  • 21
  • 38
0

Question 1: In standard TypeScript-based tools such as tsc and Visual Studio Code that process an entire project, a module augmentation like yours in any file of your project (based on the files, include, and exclude settings in tsconfig.json) is automatically in effect for all files in your project that use the original module; there is no need to explicitly reference the file containing the augmentation. However, ts-node defaults to only passing files to TypeScript as they are loaded at runtime (documentation). You can use the --files option to get ts-node to pass the entire project to TypeScript. (This will be enough for your module augmentation to work, though note that this still does not eagerly load all files at runtime. To do that, you would have to use import or require, and then you'd no longer need --files.)

Matt McCutchen
  • 28,856
  • 2
  • 68
  • 75