error TS2582: Missing types in a TypeScript project

This is a quick note as a pointer to anyone running into type errors like error TS2582. You might be working with Jest, TypeScript, and a monorepo setup, using something like lerna. I was porting over some projects into a monorepo and had a tsconfig.json issue which was cause for this error. You might be seeing errors similar to: error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try npm i --save-dev @types/jest or npm i --save-dev @types/mocha.

As it turns out, my issue was that I had a tsconfig.json file with typeRoots configured to point to the package’s own node_modules directory. Like this:

  "compilerOptions": {
    "...": "...",
    "typeRoots": ["./node_modules/@types"]

As this was a monorepo, common types such as those from jest were installed in the repository root. Meaning a package tsconfig.json file under package/example-package, referencing the location of “./node_modules/@types” was incorrect.

The fix was to simply remove the typeRoots setting from the package, or change it to point a further level down to the root: “../../node_modules/@types“.

To quote the docs on typeRoots, if you explicitly set typeRoots, then you’re narrowing down the locations that these will be pulled in from (compared to the default of not setting them).

By default all visible@types” packages are included in your compilation. Packages in node_modules/@types of any enclosing folder are considered visible. For example, that means packages within ./node_modules/@types/, ../node_modules/@types/, ../../node_modules/@types/, and so on.

TypeScript TSConfig Reference