bajankristof / nedb-promises

A dead-simple promise wrapper for nedb.
MIT License
298 stars 45 forks source link

TypeScript (plus suggestions and auto import in VS Code) fail due to inaccurate TypeScript declaration #56

Closed jordanbtucker closed 2 years ago

jordanbtucker commented 2 years ago

index.d.ts declares a default export, however nedb-promises does not have a default export.

When using import Datastore from 'nedb-promises', TypeScript will not throw an error when compiling, but the resulting JavaScript will throw an error when ran.

import Datastore from "nedb-promises"

const db = Datastore.create({filename: 'data.db'})
const db = Datastore.create({filename: 'data.db'})
                     ^

TypeError: Cannot read properties of undefined (reading 'create')

Note that this will not throw when tsconfig.json contains esModuleInterop: true, however this is not the default.


This also causes VS Code to incorrectly import nedb-promises in TypeScript and JavaScript projects.

image

image

Since index.d.ts tells VS Code that nedb-promises has a default export, VS Code suggests members that don't actually exist (because nedbPromises.default does not exist).

image

const db = nedbPromises.create({filename: 'data.db'})
                        ^

TypeError: Cannot read properties of undefined (reading 'create')

When the correct require statement is used, VS Code displays incorrect suggestions.

image


The solution to this is to use the export = syntax in index.d.ts. This will inform TypeScript that nedb-promises' export is not an ECMAScript Modules default export but a CommonJS export. TypeScript users must then use the import = require() syntax to import nedb-promises, or set esModuleInterop: true in tsconfig.json if they want to use the import from syntax to import nedb-promises.

TypeScript will inform the user of this in an error message when compiling if they try to using import from without esModuleInterop: true, so this will catch the resulting runtime error before it can occur.

This will also cause VS Code to auto import nedb-promises correctly in TypeScript and JavaScript projects.

bajankristof commented 2 years ago

Released with 6.0.3 to NPM. Thanks again for the issue and the PR!