'typeRoots' fails to find d.ts declaration files in project

Viewed 603
// tsconfig.json inside "compilerOptions"
    "typeRoots": ["./@types", "./node_modules/@types"],

// {projectRoot}/@types/express/index.d.ts
declare global {
  namespace Express {
    interface Request {
      verifiedAccessToken: string
    }
  }
}

In another file with req annotated to Request inside the function parameter, I am still not able to set verifiedAccessToken without a lint error in VsCode:

req.verifiedAccessToken = accessToken;
// Property 'verifiedAccessToken' does not exist on 
// type 'Request<ParamsDictionary, any, any, ParsedQs>'.ts(2339)

Anything else that needs to be done for the declaration file to be used?

// package.json, relevent deps
 "dependencies": {
    "express": "^4.17.1",
    "node-typescript": "^0.1.3",
    "ts-node": "^9.0.0",
    "typescript": "^3.9.7"
  },
  "devDependencies": {
    "@types/express": "^4.17.8",
    "@types/node": "^14.0.27",
2 Answers

I followed the accepted answer's link and still had issues. So, for the future searcher, here's my answer (copy/pasted from my comment in the Github issue):

@gaurav5430's comment got me on the right track!

My original folder layout:

@types/
 index.d.ts
src/
 index.ts
package.json
tsconfig.json

My tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": "./",
    "declaration": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "outDir": "dist",
    "paths": {
      "*": [
        "@types/*"
      ]
    },
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types",
      "@types"
    ],
  },
  "include": [
    "src/**/*"
  ]
}

I was still getting errors and I could not understand why. Turns out, @types/index.d.ts should actually be named after the module that doesn't have types. So, for me I had to change: @types/index.d.ts to @types/csv-to-js-parser.d.ts.

(Contents of that file being declare module "csv-to-js-parser";)

FINALLY

Also, this issue is super annoying.

Related