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?