The global declaration of Typescript is only accessible within the node_modules/@types directory

Scenario

As I develop an npm package using Typescript, I include types that are shipped alongside the library in the following structure:

my-package
|- index.js
|- index.d.ts
|- package.json

The index.d.ts file includes global declarations like:

declare var thisIsAGlobal: string

The Issue

Upon publishing and installing the package in another project with npm i my-package, the global types are not recognized by Typescript unless explicitly importing 'my-package' or adding

/// <reference types="my=package"
in any file within the project. After doing so, the global types become visible.

Project setup:

- node_modules
 |- my-library
   |- index.d.ts
- src
 |- index.ts  // thisIsAGlobal global not visible
 |- other_file.ts // thisIsAGlobal global not visible

Findings

While examining Jest type exports, which mostly consist of globals, I noticed a contrast between Jest globals and mine—notably the location. Jest globals reside in

node_modules/@types/jest/index.d.ts
, while mine are located outside of node_modules/@types. Initially, I suspected an issue related to package.json or certain type configurations. To test this theory, I conducted an experiment:

I manually created a single file (with a global variable) inside a folder within node_modules/@types, and the global was successfully accessible in my project files.

- node_modules
 |- @types
   |- experiment
     |- index.d.ts  // declare var thisIsAGlobal: number

If I relocate the experimental file outside the @types directory, the global variable becomes invisible within the project files.

- node_modules
 |- @types
 |- experiment
   |- index.d.ts  // declare var thisIsAGlobal: number

Remarkably, no package.json file is required within the @types directory for Typescript to recognize global types.

Inquiry

Could there be some oversight on my part regarding publishing a package with global types?

Do non-@types types necessitate special configurations?

Answer №1

When using TypeScript, the default behavior is to always scan the `node_modules/@types` directory:

All visible "@types" packages are included in your compilation by default. This includes packages in node_modules/@types of any enclosing folder. -- https://www.typescriptlang.org/tsconfig#types

You can confirm that @types are being included unconditionally (based on the default tsconfig.json) by running `tsc --traceResolution`.

It has been observed that only packages from `node_modules` are scanned when you actually import something from them. While there is no clear explanation as to why all `node_modules` packages are not scanned by default, it seems logical to avoid unnecessary scanning of every package in `node_modules` for types. Moreover, any types (global or otherwise) from those packages will only be relevant if they are imported. It is more reasonable to scan @types by default to gather global types for libraries like node (@types/node) that are implicitly used but not necessarily imported. Another point to consider is that importing types from all node_modules by default could lead to potential collisions.

The documentation mentions that if you want to import global declarations from a "global library" without actually importing anything from it, you should use:

/// <reference types="someLib" />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for using nodemon to automatically restart multiple server files in npm script when making changes to the files:

Whenever I make edits to a file in the specified folder, I need the two server files to restart using nodemon within an npm script. Below is the npm script: "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": ...

Ways to turn off a TypeScript error across the entire project

Due to an unresolved TypeScript bug causing a false positive, I am looking to disable a specific TypeScript error for my entire project. How can this be achieved? The requirements are: Disabling only one type of error Not limited to a single line or file ...

Tips for testing the setTimeout function within the ngOnInit using Jasmine

Could someone please assist me with writing a test for an ngOnInit function that includes a setTimeout() call? I am new to jasmine test cases and unsure of the correct approach. Any guidance would be greatly appreciated. app.component.ts: ngOnInit(): void ...

In Angular with rxjs, make sure the response is set to null if the json file cannot be found during an http.get request

When working on my Angular app, I often retrieve data from a static JSON file like this: @Injectable() export class ConfigService { constructor(private http: HttpClient) { } getData() { this.http.get('/assets/myfile.json').subscribe(da ...

Guide for retrieving a user object from an HTTP request

I am looking to retrieve only the user object from the request. public async getUserByHash(hash: IHash) { this.logger.log('Hash for check email accessed'); const user = await this.hashRepository.findOne({ select: ['id', ...

Unfamiliar XML nodes being parsed by NodeJS xml-stream

I am in search of a robust tool to handle the parsing of large XML files, and recently stumbled upon xml-stream. While it is quite powerful, I am encountering an issue where it requires me to specify the expected field for unknown nodes. Here is an exampl ...

Utilize Angular 9 to fetch data from an API using the Get method, map them to a class, and

Seeking to extract information from a test URL and convert the data into a list, I aim to exhibit them in an alert/Loop for testing purposes. The dummy API URL being used is: The returned data follows this structure: {"status":"success","data":[{"id":"1" ...

Encountering TAR_BAD_ARCHIVE and TAR_ENTRY_INVALID errors while attempting to npm install a package

I attempted to remove npm_cache and update the latest version of npm, but unfortunately, it didn't resolve the issue. I've exhaustively searched for solutions to this specific error but haven't found any that work. Oddly enough, I can execut ...

Encountering permission issues while trying to run yo @superset-ui/superset

Exploring ways to customize Apache Superset, I came across this page: With the command 'yo @superset-ui/superset', I encountered the following error: /usr/lib/node_modules/yo/node_modules/write-file-atomic/index.js:236 throw err ^ Error ...

Making the right choice: Class vs Interface in your Angular project

Today, I find myself pondering a question regarding classes and interfaces in Angular. In my opinion, here is my take on the matter: Interfaces are utilized in Typescript for type-checking purposes, existing until transpilation and disappearing in produc ...

Implementing redux-persist with redux toolkit using TypeScript

Currently, I have been utilizing Redux Persist in my next js application but now I am interested in incorporating redux toolkit with TypeScript. While I have managed to grasp the syntax for implementing redux-persist in redux toolkit, I am struggling to ...

The module was not found: Unable to locate the file './AppAPI' in the project directory

Despite setting up my react app correctly, I keep encountering an error. I have all my code in a file called App.API.js within the src folder. The issue seems to be originating from the index.js file, where the code is: import App from './AppAPI&apo ...

I encountered an issue during the installation of react-typical via npm

Oops! An error occurred: C:\Users\aselemidivine\Desktop\portfolio_website-STARTER> npm i react-typical npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi ...

Error encountered: npm ERR! The function cb.apply is not defined when conducting the command npm install @angular/cli@latest

I encountered an issue with the message "npm ERR! cb.apply is not a function" on Windows while running the following command: > npm install I also attempted to resolve it by using: > npm install @angular/cli@latest However, the error persis ...

Cannot repair npm error message indicating that re-evaluating native module sources is not possible

Whenever I make a call to npm, a barrage of messages shows up: fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version. I've searched through various threads here ...

How to add a nodejs package without relying on npm installation

Hello, I am facing an issue with a module that I have stored as a tar.gz file in a directory. When I tried to install it using the command below: npm install foo.tar.gz -g The installation failed and I received an error stating that the folder is not ava ...

What type is the appropriate choice for this handler?

I´m struggling to select the right type for this particular function. It serves as an async handler for express js in a project that utilizes typescript and eslint for linting with specific rules. export function asyncHandler( handler: any ): (req: Requ ...

Creating a unified environment variable for Angular 2 and ASP.NET Core MVC: A comprehensive guide

In my ASP.NET Core MVC project, I am utilizing an Angular 2 application. Both the Angular 2 app and the Startup.cs file contain code that is specific to different environments. For example, using http://localhost as the web service URL during development ...

Entrypoint Docker Script catering to the execution of either npm config, npm run, or both commands

When conducting tests with TestCafe and CucumberJS using Docker, which is built on top of Node.js, the test runs are initiated via npm scripts. The workflow includes... 1) Pulling a pre-built Docker image from Git 2) Optionally setting a 'config&apo ...

The execution time of Node's Promises.all() function is unreasonably slow

I need to add a table containing data on sent emails after each email has been successfully sent. Within a loop, I am populating an array to be resolved using the Promise.all(). insertData is a function that adds data, requiring two parameters: connector, ...