Incorrect Types when using in a TypeScript ESM project
pkerschbaum opened this issue Β· comments
π Version & Regression Information
1.2.0
β― Playground Link
https://stackblitz.com/edit/node-3rxg4d
- Run
npm install
. - Run tsc compilation via
npm run build
. The error occurs.
π» Code
import invariant from 'tiny-invariant';
invariant(typeof 'foo' === 'string');
π Actual behavior
I tried to run the code above from a TypeScript ESM package, this means:
"type": "module"
set inpackage.json
"module": "node16"
set intsconfig.json
But in such a project, the code does not compile:
β― npm run build
$ tsc
src/test.ts:3:1 - error TS2349: This expression is not callable.
Type 'typeof import("/home/projects/node-3rxg4d/node_modules/tiny-invariant/dist/tiny-invariant")' has no call signatures.
invariant(typeof 'foo' === 'string');
Found 1 error in src/test.ts:3
Note that the compiled output does run as expected, so the only problem is the TypeScript compilation error.
π Expected behavior
The code should compile.
I think the root cause is the same as this: microsoft/TypeScript#50690.
I ran into this one today as well! What can I do to fix this?
Seems like we must get TypeScript into "ESM" mode when importing tiny-invariant
.
I know two solutions:
- Modify build to output
dist/tiny-invariant.mjs
anddist/tiny-invariant.d.mts
(note the file extensionsmjs
andmts
). And configure conditional exports (nodejs.org/api/packages.html#conditional-exports). - Modify build to output
dist/node16/tiny-invariant.js
anddist/node16/tiny-invariant.d.ts
, and put apackage.json
there with"type": "module"
set.
And configure conditional exports.
Because JS files are considered ESM modules when the "nearest" package.json contains this property.
Approach 2 is what safe-stable-stringify does.
The problem with approach 1 is that it is difficult to output dist/tiny-invariant.d.mts
without creating a src/tiny-invariant.mts
file.
I would go with approach 2, I will create a PR with it - have almost done it already :)