I have an external library thing.d.ts
file with a global definition inside:
declare var thing: ThingStatic;
export default thing;
I reference npm module in my TypeScript:
import thing from 'thing';
...
thing.functionOnThing();
When I transpile the TS (targeting ES6) it looks something like this:
const thing_1 = require("thing");
...
thing_1.default.functionOnThing();
This then throws an error:
Cannot read property 'functionOnThing' of undefined
Why is TypeScript adding .default
between thing_1
and functionOnThing()
?
There is no property named default
on ThingStatic
, and no default
property on the underlying JS object that the .d.ts
file defines.
Why is TypeScript adding the property and how do I stop it?
This appears to be a bug with global TS definitions and
"module": "commonjs"
in thetsconfig.json
.You can either use global TS definitions and stitch all your output into a single file, or you can use modules and directly import them.
The error here is due to the
require
returning the module context, and the name of thedefault
being irrelevant - it always becomesdefault
...Now
require
will return this context, so withcommonjs
modules:However, I've found this to be inconsistent, so switched to es6 modules: