TSError: ⨯ Unable to compile TypeScript:
test/mainTest.ts:3:17 - error TS2552: Cannot find name 'myGlobal'.
This is happening because ts-node
isn’t looking for global.d.ts
file. After
doing some research the first time I ran into this, I found two common
suggestions:
Pass the --files
flag to ts-node
so ts-node
will compile all TypeScript
files defined by your tsconfig
s files
key. The large downside here being
that each time you use ts-node
all of those files will be compiled
resulting in slower startup time.
Define typeRoots
. Again, this works, but you no longer have automatic type
declaration detection.
Because of the downsides each solution came with, I searched for a better
approach and thankfully, found one. Well, two.
The first option was to use a triple slash
directive to associate the file that declares the global value with the declaration file.
/// <reference types="./global" />
global.myGlobal = 100
Note: Omit the .d.ts
file extension.
This effectively says ‘this file depends on these types, when importing me
please import the types too’. Running npx tsc
completed successfully, as did
our ts-node
powered mocha tests.
The next solution seemed almost obvious after I found it. The global.d.ts
file
can be imported.
import "./global.d"
global.myGlobal = 100
Now running tsc
and our ts-node
script, both complete successfully.
It took a bit of trial, error, and google, but I’m pretty happy with how simple
the solution ended up being.