I'm creating a Chrome extension using TypeScript and have hit a snag. Everything was working fine initially, but when adding a new dependency (webpack), the type definitions it brings in cause my working scripts to now produce compilation errors where the Node types conflict with Chrome types.
The problem can be seen by following these steps:
mkdir type-conflict && cd type-conflict
npm init
npm install -D @types/chrome typescript
npx tsc --init
echo 'const timeout: number = setTimeout(() => console.log(timeout), 0);' > example.ts
npx tsc
— this works just fine and produces example.jsnpm install -D @types/webpack webpack
— this brings in the Node types transitivelynpx tsc
— this time, you get the error "example.ts(1,7): error TS2322: Type 'Timeout' is not assignable to type 'number'."The only script I want to see the Node types is the webpack configuration script itself, which has its own tsconfig-for-webpack-config.json
; how can I get TypeScript to ignore those types in the main tsconfig.json
so that my scripts can use the browser types again?
As jonrsharpe said in the comments, explicitly set the types
property in tsconfig.json. Docs on that here:
By default all visible "
@types
" packages are included in your compilation.[...]
If
types
is specified, only packages listed will be included in the global scope.
E.g. (different from docs)
{
"compilerOptions": {
// Setting to empty array is a valid option too.
// Just don't forget to declare the ones you need for the web app
// E.g. three.js requires you to install @types/three for TS code
"types": ["three"]
}
}
You indicated that the webpack has its own tsconfig. For vite (what I'm using), it looks like this is also the case, so it works without having to make a separate tsconfig. As a bonus, it de-clutters the autocompletion of VSCode, which is also nice.