Eliya Cohen
Eliya Cohen

Reputation: 11458

Getting repetitive "Cannot find type definition" error on VS Code, but not in TSC

I have an app based on NextJS using Typescript (which is based on React).

I found myself installing npm i -D @types/XXX enough times to figure out that something isn't right. After looking at my tsconfig.json file, I noticed that compilerOptions.typeRoots was missing, so I added the following lines:

{
    "compilerOptions": {
        ...
        "typeRoots": [
            "node_modules"
        ]
    }
}

After restarting my IDE, I could finally get the type declarations of my packages without manually installing the types. But, there's an issue when VS Code screams I have 448 problems (which is the same problem all over):

what the f*** vsc?

to make sure it's not actually TSC problem, I ran next dev which basically runs tsc (among other things) and it runs without any issue. I'm a bit confused...

Upvotes: 1

Views: 1789

Answers (1)

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30545

In general, types are seperate npm packages, so you need to manually install them. beside of this

{
    "compilerOptions": {
        ...
        "typeRoots": [
            "node_modules"
        }
    }
]
}

has syntax error

{
    "compilerOptions": {
        ...
        "typeRoots": [
            "node_modules"
        ]
    }
}

this is my typeRoots configuration

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

first one is for local types and the latter is for installed node module types.

EDIT:

If you have some packages which doesn't have types, you have three option:

  1. create type declarations by implementing them properly

declare module "@ampproject" { export function some_function(str: string): string; };

  1. create global.d.ts inside types directory and add declare module "*" or just for @ampproject declare module "@ampproject";
  2. cast object to any

Upvotes: 2

Related Questions